1. Member
Join Date
Feb 2013
Posts
2
Rep Power
0

## InputMismatchException Error

Hello,
I'm trying to do a simple calculator, but I have some problems about getting double input. I am running the code and enter the input (like 5+4) then it returns

java.util.InputMismatchException
Scanner.nextDouble(Unknown Source) errors.
The error is shown when getting the firstNum //firstNum = input.nextDouble();
Thank you for your time and helps.

Here is my code:

Java Code:
```import java.util.Scanner;

public class Main {

public static void main(String[] args) {
double firstNum;    // First number in the expression.
double secondNum;   // Second number in the expression.
char operator;      // The operator in the expression.
double value;       // The value of the expression.

System.out.println("Enter expressions such as  2 + 2  or  34.2 * 7.81");
System.out.println("using any of the operators +, -, *, /.");
System.out.println("To end, enter a 0.");

Scanner input = new Scanner(System.in);

while (true) {

/* Get user's input, ending program if first number is 0. */

System.out.println("? ");
firstNum = input.nextDouble();

if (firstNum == 0)
break;
operator = input.findInLine(".").charAt(0);
secondNum = input.nextDouble();

/* Compute the value of the expression. */

switch (operator) {
case '+':
value = firstNum + secondNum;
break;
case '-':
value = firstNum - secondNum;
break;
case '*':
value = firstNum * secondNum;
break;
case '/':
value = firstNum / secondNum;
break;
default:
System.out.println("Unknown operator: " + operator);
continue;  // Back to start of loop!
} // end switch

/* Display the value. */

System.out.println("Value is " + value);
System.out.println();

} // end while

System.out.println("Good bye");
}
}```

2. ## Re: InputMismatchException Error

Did you read the Scanner API doc for nextDouble()? 5+4 is not a valid number in double format. Either you read the whole expression with nextLine() and then try to identify the two numbers and the operand, or you read the three values individually.

3. Member
Join Date
Feb 2013
Posts
2
Rep Power
0

## Re: InputMismatchException Error

Yes, I read that. I also used int instead of double but it again gives the same error. I think there is an assignment problem but I can not find it.

4. ## Re: InputMismatchException Error

5+4 isn't an int either ist's a string literal. Read my previous reply.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•