我想讓用戶輸入兩個數字,如果輸入了無效字符,我希望程序要求用戶再次輸入一個數字。爲什麼我的做法不正確?爲什麼這個循環直到輸入一個整數纔會查找輸入?
import java.util.InputMismatchException;
import java.util.Scanner;
public class Calculator {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
double answer = 0;
boolean goodInput = false;
do {
try{
System.out.println("Enter your first number:");
double firstNum = input.nextDouble();
System.out.println("Enter your second number:");
double secondNum = input.nextDouble();
System.out.println("Which operation would you like to use?");
System.out.println("For addition, type add");
System.out.println("For subtraction, type subtract");
System.out.println("For divison, type divide");
System.out.println("For multiplication, type multiply");
String operation = input.next();
goodInput = true;
if (operation.equals("add")) {
answer = firstNum + secondNum;
System.out.println(firstNum + " + " + secondNum + " = "+ answer);
}
if (operation.equals("subtract")) {
answer = firstNum - secondNum;
System.out.println(firstNum + " - " + secondNum + " = "+ answer);
}
if (operation.equals("divide")) {
answer = firstNum/secondNum;
System.out.println(firstNum + "/" + secondNum + " = "+ answer);
}
if (operation.equals("multiply")) {
answer = firstNum * secondNum;
System.out.println(firstNum + " x " + secondNum + " = "+ answer);
}
}catch(InputMismatchException e) {
System.out.println("Thats not a number, enter a number:");
}
}while(goodInput = false);
}
}
您在這裏爲'goodInput'賦值新值:'goodInput = false'而不是'!goodInput' – Multithreader 2014-09-18 23:19:10