我正在做一个编程任务,询问用户一些问题,如果用户得到错误/正确的答案也没关系,随机数生成器用于确定他们对该问题的分数。然而,如果他们选择“不可能的答案”(这是不可能的事情,他们的分数将重置为 0。
当我运行代码时,
如果我在第一个问题上得到 23 分,在第二个问题上得到 0 分,那么我在第二个问题上的得分应该重置为 0,但最终总得分显示为 23。
如有任何帮助,我们将不胜感激
import java.util.Scanner;
public class Main {
public static double randnum(){
int random = (int)(Math.random() * 50 + 1);
return random;
}
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
int score1 = 0;
int score2 = 0;
int score3 = 0;
int totalscore = 0;
final double NumberofQuestions = 2;
String[][] questions ={
{"What is the largest bone in the human body? ", "\n Choose 1 for Femur \n Choose 2 for Tibia \n Choose 3 for Palatine Bone \n Choose 4 for Tongue ", "1"},
{"What is the capital of Albania? ! ","\n Choose 1 for Shkoder \n Choose 2 for Tirana \n Choose 3 for Durres \n Choose 4 for Rome ", "2"}
};
String[] Answers = new String[(int) NumberofQuestions];
int x=0;
do
{
System.out.print("" + (x+1) + ". " + questions[x][0] + " "+questions[x][1]);
Answers[x] = String.valueOf(input.nextInt());
Answers[x].toLowerCase();
if(questions[x][2].equals(Answers[x])) {
score1 = (int) randnum();
System.out.println("Correct: " + score1 + " points");
totalscore = totalscore + score1;
}
if (Answers[x].equals("4")){
System.out.println("\n Thats a impossible answer! The right answer is "+questions[x][2]);
totalscore = 0;
score2 = 0;
System.out.println(score2 + " points");
} else {
System.out.println("\nIncorrect. The right answer is "+questions[x][2]);
score3 = (int) randnum();
System.out.println(score3 + " points");
totalscore = totalscore + score3;
}
System.out.print("\n");
x++;
} while(x < NumberofQuestions); //close outer loop
totalscore = score1 + score2 + score3;
System.out.println("\n\t\tYou got " + totalscore + " points !\n\n\n");
System.exit(0);
}
}
最佳答案
快速修复当前代码的问题:
- 如果用户选择不可能的答案,请将所有分数变量设置为 0,而不仅仅是 Score2
将 do/while 循环更改为简单的 while 循环:
while(x<NumberofQuestions) { …
而不是:
do { ...
另请注意,您在仅提出 2 个问题时使用了 3 个分数变量
关于java - Do-while 循环未打印正确的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58696406/