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);
}
}}}
Your calling next() on scanner without checking with hasNext()
while(input.hasNext())
{
num1 = Double.parseDouble(input.nextDouble());
num2 = Double.parseDouble(input.nextDouble());
......//further code
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With