[英]I can't figure out to print if input is empty or not
So I made a program, which loops 2 questions from an array.所以我做了一个程序,它从一个数组中循环 2 个问题。 What I want to happen here is to prompt if the user entered blank or empty, and also if the user inputs any other letter, number or symbol aside from a, b, and c.
我想要在这里发生的是提示用户是否输入了空白或空,以及用户是否输入了除 a、b 和 c 之外的任何其他字母、数字或符号。 What's happening here is whenever I input a on the first question it also prints "That answer can't be blank" which it shouldn't since I entered a valid input.
这里发生的事情是,每当我在第一个问题上输入 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++;
}
}
your code should look something like this...你的代码应该是这样的......
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++;
}
}
What I have changed in the code: removed multiple ifs, instead used if-else, and removed !
我在代码中所做的更改:删除了多个 if,而是使用了 if-else,并删除了
!
from !answer.isEmpty()
.来自
!answer.isEmpty()
。 Hoping this will help you :-)希望这会帮助你:-)
happy coding快乐编码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.