java如何循环文件中的问题
我的程序应该从文件中提取问题并打印它们和答案。然后用户应该回答他们,如果他们答错了,程序应该扣分。每个问题值5分,如果答错了,你就输了2分但是当你出错时,它应该不断地问你这个问题,而不是继续问下一个问题,我该如何解决这个问题?并向用户显示他们还剩下多少点强>
import java.util.Scanner;
public class HW21 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
HWData hd = new HWData();
int currentScore = 5;
int numberOfQuestions = hd.getNumberOfQuestions();
for (int questionIndex=0; questionIndex<numberOfQuestions; ++questionIndex) {
System.out.println(hd.getQuestion(questionIndex));
System.out.println();
System.out.println("1. " + hd.getAnswer1(questionIndex));
System.out.println();
System.out.println("2. " + hd.getAnswer2(questionIndex));
System.out.println();
System.out.println("3. " + hd.getAnswer3(questionIndex));
System.out.println();
System.out.println("4. " + hd.getAnswer4(questionIndex));
int answer = input.nextInt();
if (answer == hd.getCorrect(questionIndex)) {
System.out.println(" Great Job! You got the right answer!");
}
else {
System.out.println(" You got the answer wrong.");
currentScore -= 2;
}
}
input.close();
System.out.println("Final score: " + currentScore);
}
}
# 1 楼答案
另一个解决方案是将questionIndex减少1,以便循环保持在相同的位置,直到用户正确地获得它。 大概是这样的:
# 2 楼答案
我给了你一些伪代码,让你通过。这听起来像是一个家庭作业,因此我不会在这里发布完整的代码
1. Get number of questions 2. Initialize totalScore to 5 // I am taking this from your code snippet 2. For all questions, repeat steps 3. Ask Question i 4. if answer(i) == correct totalScore = totalScore + 5 Move on to next question Else, totalScore = totalScore -2 Print totalScore Go back to Step 3 5. At this step, the loop is done. Print totalScore or whatever actions you need to do
是的,
Go back
部分需要使用一些flag
变量来指示答案是否正确我希望你现在能解决这个问题。顺便说一下,总的来说,你的代码看起来还不错。你在正确的道路上