gpt4 book ai didi

java - java中的数组循环

转载 作者:行者123 更新时间:2023-12-01 19:06:06 25 4
gpt4 key购买 nike

我尝试主要使用数组来编写此代码。我试图在每个问题后显示“正确”或“不正确”,并在最后获得正确/不正确的答案总数。目标是使用数组来完成此任务,但我不知道如何使用数组在每个问题后显示正确/不正确。

//Declarations
String rightAnswer[] = { "B", "C", "A" };
String userAnswer[] = new String [3];
String answer;
int counter;
int finalInt = 3;
int index = 0;
int correct = 0;
int incorrect = 0;

// detailedLoop
for(index = 0; index < finalInt; index++) {
do {
answer = JOptionPane.showInputDialog("What planet has the largest rings? \n\nA. Neptune \nB. Saturn \nC. Jupiter");
userAnswer[index] = answer;
} while(!(answer.equals("A")|| answer.equals("B") || answer.equals("C")));

index++;
do {
answer = JOptionPane.showInputDialog("What planet has a large redspot? \n\nA. Neptune \nB. Saturn \nC. Jupiter");
userAnswer[index] = answer;
} while(!(answer.equals("A")|| answer.equals("B") || answer.equals("C")));

index++;
do {
answer = JOptionPane.showInputDialog("What planet is farthest from the sun? \n\nA. Neptune \nB. Saturn \nC. Jupiter");
userAnswer[index] = answer;
} while(!(answer.equals("A")|| answer.equals("B") || answer.equals("C")));

if(userAnswer[index].equals(rightAnswer[index])) {
System.out.println("Correct!");
correct++;
index++;
}
if(!(userAnswer[index].equals(rightAnswer[index]))) {
System.out.println("Incorrect. The right answer is " + rightAnswer[index] + ".");
incorrect++;
index++;
}
}
System.out.println("Total correct:" + correct + ". Total incorrect: " + incorrect + ".");

感谢任何帮助,谢谢。

最佳答案

这可能是您想要做的,再次,我不完全理解这个问题:

String questions[] = {
"What planet has the largest rings? \n\nA. Neptune \nB. Saturn \nC. Jupiter",
"What planet has a large redspot? \n\nA. Neptune \nB. Saturn \nC. Jupiter",
"What planet is farthest from the sun? \n\nA. Neptune \nB. Saturn \nC. Jupiter"
};
String rightAnswer[] = { "B", "C", "A" };
String answer = null; // the user's answer
for (int i = 0; i < questions.length; i++) {
do {
answer = JOptionPane.showInputDialog(questions[i]);
} while (!(answer.equals("A")|| answer.equals("B") || answer.equals("C")));
String x = (answer.equals(rightAnswer[i])) ? "correct" : "incorrect.\nThe correct answer was " + rightAnswer[i];
JOptionPane.showMessageDialog(null, "Your answer was " + x + ".");
}

请原谅我的风格。

关于java - java中的数组循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10067962/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com