我希望java給我亂數,用戶會嘗試猜測它,如果用戶嘗試輸入無效的資料型別,它會說:“無效輸入。僅限整數。再試一次”并將繼續代碼,但代碼即使它有while回圈,在顯示訊息后也沒有推送。
我的整個選擇:
import java.util.*;
public class tine {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Random ranNum = new Random();
boolean Win = false;
int nAttempt = 0;
int number = (int)(Math.random()*50 );
int userInput;
System.out.println("Guess a number from 1-50!");
while (Win == false) {
nAttempt ;
try {
userInput = sc.nextInt();
if (userInput < number && userInput >= 1) {
System.out.println("too low.");
}
else if (userInput > number && userInput <= 50){
System.out.println("too high");
}
else if (userInput == number) {
System.out.println("you got it right in " nAttempt " attemp(s)");
Win = true;
}
else {
throw new InvalidInputException();
}
}
catch (InputMismatchException im) {
System.out.println("Invalid Input. Integer only. Try Again");
userInput = sc.nextInt();
nAttempt--;
}
catch (InvalidInputException iie) {
System.out.println("Number is out of range. Try Again.");
userInput = sc.nextInt();
nAttempt--;
}
}
}
}
class InvalidInputException extends Exception {
InvalidInputException(){
super();
}
}
uj5u.com熱心網友回復:
根據Scanner 上的 java API 規范:
Scanner 使用分隔符模式將其輸入分解為標記,默認情況下匹配空格。
雖然nextInt()這樣做:
將輸入的下一個標記掃描為 int。
因此,包含空格的輸入將被視為多個輸入,可能無法按預期作業。
為了解決這個問題,我建議使用 掃描整行Scanner.nextLine(),它“回傳當前行的其余部分,不包括末尾的任何行分隔符”;然后將該行決議為帶有 的整數Integer.parseInt(String),這會在非法模式上引發運行時例外NumberFormatException,因此不妨將其包含在 catch 陳述句中:
try
{
String ln = sc.nextLine();
userInput = Integer.parseInt(ln);
...
}
catch (InputMismatchException | NumberFormatException im)
{...}
catch (InvalidInputException iie)
{...}
此外,我沒有看到userInputcatch 塊內的讀取點,因為它將在 try 塊的第一行再次更新,因為 while 回圈的另一個回圈開始了。因此,我建議洗掉它們:
catch (InputMismatchException im)
{
System.out.println("Invalid Input. Integer only. Try Again");
// userInput = sc.nextInt();
nAttempt--;
}
catch (InvalidInputException iie)
{
System.out.println("Number is out of range. Try Again.");
// userInput = sc.nextInt();
nAttempt--;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/457668.html
