[英]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.