[英]I can't seem to figure out what to do with this instance so that my code could print out the requirement
[英]I can't figure out to print if input is empty or not
所以我做了一個程序,它從一個數組中循環 2 個問題。 我想要在這里發生的是提示用戶是否輸入了空白或空,以及用戶是否輸入了除 a、b 和 c 之外的任何其他字母、數字或符號。 這里發生的事情是,每當我在第一個問題上輸入 a 時,它也會打印“那個答案不能為空”,因為我輸入了一個有效的輸入,它不應該是空的。
for(int i = 0; i < question.length; i++){
do{
System.out.print(question[i].prompt + "\nAnswer: ");
answer = s.nextLine();
if(!answer.equalsIgnoreCase("a") &&
!answer.equalsIgnoreCase("b") &&
!answer.equalsIgnoreCase("c")){
System.out.println("Invalid input!\n");
} if(!answer.isEmpty()){
System.out.println("The answer can't be blank.\n");
}
} while(!answer.equalsIgnoreCase("a") &&
!answer.equalsIgnoreCase("b") &&
!answer.equalsIgnoreCase("c") &&
!answer.isEmpty());
if(answer.equalsIgnoreCase(question[i].answer)){
score++;
}
}
你的代碼應該是這樣的......
for(int i = 0; i < question.length; i++){
do{
System.out.print(question[i].prompt + "\nAnswer: ");
answer = s.nextLine();
if(answer.isEmpty()){
System.out.println("The answer can't be blank.\n");
}else if(!answer.equalsIgnoreCase("a") &&
!answer.equalsIgnoreCase("b") &&
!answer.equalsIgnoreCase("c")){
System.out.println("Invalid input!\n");
}
} while(!answer.equalsIgnoreCase("a") &&
!answer.equalsIgnoreCase("b") &&
!answer.equalsIgnoreCase("c") &&
!answer.isEmpty());
if(answer.equalsIgnoreCase(question[i].answer)){
score++;
}
}
我在代碼中所做的更改:刪除了多個 if,而是使用了 if-else,並刪除了!
來自!answer.isEmpty()
。 希望這會幫助你:-)
快樂編碼
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.