如果用戶沒有輸入值,我想顯示一條錯誤消息,所以我使用了這個。如果你可以幫助我在用戶沒有輸入一個很好的值時顯示我的錯誤。我的if(choice.isEmpty()){}不起作用
while (!choice.equalsIgnoreCase("y") && !choice.equalsIgnoreCase("n"))
{ //start of while
if (choice.isEmpty()) {
System.out.println("Error! This entry is required. Try again."); //display error message when the user enters invalid response
}
else {
System.out.println("Error! Entry must be 'y' or 'n'. Try again."); // display error message when the user enters no response
}
System.out.print ("Continue (y/n): "); //promt users for input
choice = sc.next();
} // End of while
else部分工作,但不是if。它只是顯示空白行,當我按下輸入,我什麼都沒有輸入。這是整個程序的完整代碼。這是一款擊球平均程序。
import java.util.*;
import java.text.NumberFormat;
public class BattingAverage
{
public static void main(String[] args)
{
System.out.println("Welcome to the Batting Average Calculator.");
System.out.println();
Scanner sc = new Scanner(System.in); // scanner for input
String choice = "y"; // initialize string
while (choice.equalsIgnoreCase("y")) //start of while to continue while the user answers y to the continue prompt below
{
int numberOfTimesAtBat;
System.out.print("Enter Number of times at bat: ");
numberOfTimesAtBat = sc.nextInt();
System.out.println("\n" + "0 = out, 1 = single, 2 = double, 3 = triple, 4 = home run");
int[] atBats = new int[numberOfTimesAtBat];
for(int counter = 0; counter < numberOfTimesAtBat; counter++){
System.out.print("Result for at-bat "+(counter+1)+": ");
atBats[counter] = sc.nextInt();
} //End of for
int sum = 0;
for (int i=0; i < atBats.length; i++) {
sum += atBats[i];
}
double Avg = sum/atBats.length;
// System.out.print("Batting average:");
System.out.print("Slugging percent: " + Avg);
System.out.print ("\n" + "Continue (y/n): "); //promt users for input
choice = sc.next(); //make choice the next input
while (!choice.equalsIgnoreCase("y") && !choice.equalsIgnoreCase("n"))
{ //start of while
if (choice.isEmpty()) {
System.out.println("Error! This entry is required. Try again."); //display error message when the user enters invalid response
}
else {
System.out.println("Error! Entry must be 'y' or 'n'. Try again."); // display error message when the user enters no response
}
System.out.print ("Continue (y/n): "); //promt users for input
choice = sc.next();
} // End of while
} // end of while
} //end of main
} // end of class
你的意思是「用戶沒有輸入數值」。在控制檯用戶必須輸入一個字符繼續。你的意思是一個空格或返回 –
考慮將常量首先放在if條件中(即「n」.equalsIgnoreCase(選擇))。這樣,如果由於某種原因選擇爲null,則不會有NullPointerException。 – AHungerArtist