我正在用java语言为学校做一个测验项目,我被卡住了。
问题是,我必须做一个while循环,检查用户的答案是否匹配正确的答案,然后打印出他们是否正确的分数。在while循环中,一旦它将useranswer与if语句中的一个答案匹配,它就会永远打印出相同的语句。所以,我尝试在if语句中使用一个布尔值来解决这个问题,只打印一次。但是这样做会中断while循环,因为它在打印出语句之后什么都不做,程序只是停止做任何事情,因为它不会出现错误或结束,但它只是显示为空白。如何继续while循环一遍又一遍地问问题,直到键入“x”结束循环,而不必无限打印。
先谢谢你。
import java.util.Scanner;
public class miniProject {
public static void main(String[] args) {
quiz_Check();
System.exit(0);
}
//this method asks the user question and saves the answer
public static String askUser() {
Scanner scanner = new Scanner(System.in);
System.out.println("Name one of the 2020 US election candidate");
String userAnswer = scanner.nextLine();
return userAnswer;
}
//this method checks the users answer and evaluates if they were correct and then gives them a score and prints out if they were correct
public static int quiz_Check(){
String userAnswer = askUser();
int score = 0;
while(!askUser().equals("X")){
if ((userAnswer.equals("Kanye West"))){
score+=2;
System.out.println("Correct Answer! "+ userAnswer +" is worth 2 points!");
}
else if((userAnswer.equals("Donald Trump"))){
score+=42;
System.out.println("Correct Answer! "+ userAnswer +" is worth 42 points");
}
else if((userAnswer.equals("Joe Biden"))){
score+=78;
System.out.println("Correct Answer! "+ userAnswer+" is worth 78 points");
}
else{
score+=100;
}
}
return score;
}
//this method prints out the score
public static void quiz_Score(){
int score=quiz_Check();
System.out.println("The score is: "+score);
return;
}
}
1条答案
按热度按时间au9on6nz1#
问题是,循环条件从未更改:
要么是假的,要么永远是真的。
根据您当前的设计,您只需不断询问答案,直到用户返回“x”
和