我在此代码中遇到输入 mistmatch 异常可以帮助我。(线程"main" java.util.InputMismatchException中的异常)


Scanner scan = new Scanner(System.in);
System.out.println("What shoud you Do deposite or withdrowal. then type D for deposite and W for withdrow");
boolean D = scan.nextBoolean();
boolean W = scan.nextBoolean();
try {
if (D == true) {
System.out.println("Enter the amount to deposite");
double amount = scan.nextDouble();
bank.deposit(amount);
} else if (W == true) {
System.out.println("Enter the amount to withdrow");
double amount = scan.nextDouble();
bank.withdrow(amount);
}
} catch(InputMismatchException e) {
System.out.println("choose the right option");
}

如果您查看Scanner.nextBoolean()源,您可以看到以下内容:

/**
* Scans the next token of the input into a boolean value and returns
* that value. This method will throw <code>InputMismatchException</code>
* if the next token cannot be translated into a valid boolean value.
* If the match is successful, the scanner advances past the input that
* matched.
*
* @return the boolean scanned from the input
* @throws InputMismatchException if the next token is not a valid boolean
* @throws NoSuchElementException if input is exhausted
* @throws IllegalStateException if this scanner is closed
*/
public boolean nextBoolean()  {
clearCaches();
return Boolean.parseBoolean(next(boolPattern()));
}

附言您的代码需要"true""false",但您打印例如数字或其他无法解析为Boolean的东西。

最新更新