Scanner doesn't wait for input after calling nextDouble()
but it works fine after nextLine()
.
import java.util.*;
public class calc {
public static final Scanner input = new Scanner(System.in);
public static void main(String[] args) {
while(true) {
calculate();
System.out.print("Would you like to run again? Y/N: ");
String repeat = input.nextLine().toLowerCase();
if (!(repeat.equals("y") || repeat.equals("yes"))) {
System.out.println("\nBye!\n");
break;
}
}
}
public static void calculate() {
System.out.print("\nAdd, Subtract, Multiply, Divide or Modulus? : ");
double fsnum, scnum, ans;
String choice = input.nextLine().toLowerCase();
if(choice.equals("add") || choice.equals("subtract") || choice.equals("multiply") || choice.equals("divide") || choice.equals("modulus")) {
System.out.print("Enter the first number: ");
fsnum = input.nextDouble();
System.out.print("Enter the second number: ");
scnum = input.nextDouble();
switch(choice) {
case "add":
ans = fsnum+scnum;
break;
case "subtract":
ans = fsnum-scnum;
break;
case "multiply":
ans = fsnum*scnum;
break;
case "divide":
ans = fsnum/scnum;
break;
case "modulus":
ans = fsnum%scnum;
break;
default:
ans = 0;
break;
}
System.out.println("The answer is: " + ans);
} else {
System.out.println("ERROR: Please select a valid operation.");
}
}
}
Output
Add, Subtract, Multiply, Divide or Modulus? : add
Enter the first number: 3
Enter the second number: 4
The answer is: 7.0
Would you like to run again? Y/N:
Bye!
As you can see the last input to run again is skipped and the program seems to assume it as "" or null.
This doesn't seem to happen if an invalid operation is chosen. -
Add, Subtract, Multiply, Divide or Modulus? : yaya
ERROR: Please select a valid operation.
Would you like to run again? Y/N: n
Bye!
Any solutions?