Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to get loop working correctly

Tags:

java

I am trying to make a calculator with a certain input that is entered like + 5 5 or / 10 2. When I compile and run it I get this error:

Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1416)
at calc.main(calc.java:11)

My Code

import java.util.Scanner;
public class calc {

public static void main(String[] args) {
    Scanner input = new Scanner( System.in );
        String calc;
        double num1;
        double calcdu = 0.0;
        double num2;
        while ( true ) {
            calc = input.next();
            num1 = input.nextDouble();
            num2 = input.nextDouble();

            if (calc.equals("+"))
            { 
                    calcdu= num1 + num2;
                    System.out.printf("%.2e %s %.2e %c %.2e\n", num1, "+", num2, '=', calcdu);
            }       

            if (calc.equals("/"))
            {   
                calcdu=num1/num2;
                System.out.printf("%.2e %s %.2e %c %.2e\n", num1, "/", num2, '=', calcdu);
            }

            if (calc.equals("-"))
            {   
                    calcdu=num1-num2;
                    System.out.printf("%.2e %s %.2e %c %.2e\n", num1, "-", num2, '=', calcdu);
            }       
            if (calc.equals("*"))
            {   
                    calcdu=num1*num2;
                    System.out.printf("%.2e %s %.2e %c %.2e\n", num1, "*", num2, '=', calcdu);
            }
            if (calc.equals("%"))
            {   
                    calcdu=num1%num2;
                    System.out.printf("%.2e %s %.2e %c %.2e\n", num1, "%", num2, '=', calcdu);
            }

}}}
like image 583
Ryan H Avatar asked Mar 17 '26 03:03

Ryan H


2 Answers

Your calling next() on scanner without checking with hasNext()

while(input.hasNext())
{
 num1 = Double.parseDouble(input.nextDouble());
            num2 = Double.parseDouble(input.nextDouble());

......//further code
like image 51
Ramanlfc Avatar answered Mar 18 '26 16:03

Ramanlfc


This exception occurs when there are no more tokens in scanner, and you try to get next, without checking. See NoSuchElementException from Java docs. In your case, as Ramanlfc mentioned, you are calling Next() on scanner without checking with if next even exists. You can use hasNext() to check if next exists.

like image 24
Zeeshan Avatar answered Mar 18 '26 16:03

Zeeshan