我以一個Java類,我可使用hasNext命令錯誤檢查兩個用戶輸入的變量,以確保他們的數字停留在分配的兩個變量。這是我迄今爲止所擁有的。問題而錯誤檢查與hasNext方法
Scanner sc = new Scanner(System.in);
String choice = "y";
double firstside;
double secondside;
//obtain user input
while (choice.equalsIgnoreCase("y")) {
System.out.println("Enter First Side: ");
if (sc.hasNextDouble()) {
firstside = sc.nextDouble();
} else {
sc.nextLine();
System.out.println("Please enter a numeric value and try again.");
continue;
}
while (true){
System.out.println("Enter Second Side: ");
if (sc.hasNextDouble()) {
secondside = sc.nextDouble();
break;
} else {
sc.nextLine();
System.out.println("Please enter a numeric value and try again.");
}
}
//calculate results
double hypotenusesquared = Math.pow(firstside, 2) + Math.pow(secondside, 2);
double hypotenuse = Math.sqrt(hypotenusesquared);
//display results
String output = "Hypotenuse = " + hypotenuse;
System.out.println(output);
System.out.println("Would you like to continue? Y/N?");
choice = sc.next();
}
}}
時出現錯誤我收到的輸出是:
請輸入一個數值,然後再試一次。輸入第一面:請輸入數字值,然後重試。進入第一面:
我打算只接收:
請輸入一個數值,然後再試一次。輸入第一面:
這是因爲你有一個大循環,要求「第一方」和「第二方」。如果你回到循環的開始,它會再次要求「第一面」,因爲這就是循環開始時的情況。你的程序沒有任何東西可以讓它回到「第二方」的問題。爲了解決這個問題,把「第二面」輸入代碼放在自己的循環中。 – ajb
爲了擴展@ajb所說的內容,'continue'關鍵字將重複整個循環,而不是再次詢問第二個變量。因此,如果您輸入的是第二個值以外的其他值,它會將您返回到開始位置。你可以把第二個輸入問題放到它自己的循環中,或者把它放在do/while循環中。 – CynePhoba12