4

So I'm trying to make a simple calculator in java but have no clue how to get an input for which operation. The program asks for two numbers, then asks for an operator. Everything works fine when i run it until i get to the operation type. The compiler just skips right over it and doesn't even let me type anything in for it. Any clues?

Scanner keyboard = new Scanner(System.in);

double x;
double y;
double sum =0;
double minus =0;
double times =0;
double divide =0;
double nCr =0;
String Op;

System.out.print("X: ");
x = keyboard.nextDouble();
System.out.print("Y: ");
y = keyboard.nextDouble();
System.out.print("Op: ");
Op = keyboard.nextLine();
Henry Keiter
  • 15,543
  • 7
  • 45
  • 76
Squash
  • 89
  • 1
  • 5

3 Answers3

2

Try:

System.out.print("X: ");
x = Double.parseDouble(keyboard.nextLine());
System.out.print("Y: ");
y = Double.parseDouble(keyboard.nextLine());
System.out.print("Op: ");
op = keyboard.nextLine();

This will parse the number you enter to Double and read the Carriage return.

If you want error control (If the user inputs a string instead of a number):

Boolean check = true;

do
{
    try
    {
        //The code to read numbers
    }
    catch(InputMismatchException e)
    {
        System.err.println("Please enter a number!");
        check = false;
    }
}
while(check == false)
Jhon
  • 573
  • 7
  • 28
  • thank you very much! It works, but i am unclear as to why it does. What exactly does parse do? – Squash May 27 '13 at 23:37
  • `keyBoard.nextLine()` will read the input as a `String`, then `Double.parseDouble` will try to parse that `String` to a `Double`. If it can't parse it, it will throw an `InputMismatchException` whenever the user inputs something that is not a number (e.g.: The user inputs 'Hello'). – Jhon May 27 '13 at 23:40
1

Instead of

Op = keyboard.nextLine();

Try using

Op = keyboard.next();

Looks like the nextLine(); method gives you a problem when invoked with methods like nextInt(), nextDouble().

Observation: If the nextLine() is invoked alone, this doesn't happen.

0

Basically the nextDouble doesn't recognize the carriage return. Use the nextLine after each nextDouble.

BlackHatSamurai
  • 21,845
  • 20
  • 84
  • 147