Why can I enter something for my operation?

So, I'm trying to make a simple calculator in java, but I don’t know how to get the input for which operation. The program asks for two numbers, then the operator asks. Everything works fine when I run it until I get to the type of operation. The compiler just slips right above it and doesn’t even let me type anything 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(); 
+4
source share
3 answers

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 check the number you enter on Double and read the carriage return.

If you need error control (if the user enters 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) 
+2
source

Instead

 Op = keyboard.nextLine(); 

Try using

 Op = keyboard.next(); 

Looks like nextLine (); The method gives you a problem when called using the methods nextInt (), nextDouble ().

Observation. If nextLine () is called alone, this does not happen.

+1
source

Basically nextDouble does not recognize a carriage return. Use nextLine after each nextDouble .

0
source

Source: https://habr.com/ru/post/1483051/


All Articles