同时执行循环未打印正确的变量

我正在执行一个编程任务,向用户询问一些问题,如果用户回答错/对都没关系,则使用随机数生成器确定该问题的分数。但是,如果他们选择“不可能的答案”(不可能的答案,那么他们的分数将重置为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);
    }    
}
flypig1025 回答:同时执行循环未打印正确的变量

快速解决当前代码问题:

  1. 如果用户选择了不可能的答案,请将所有分数变量设置为0,而不仅是score2
  2. 将do / while循环更改为简单的while循环:

    while(x<NumberofQuestions)  
    {  …
    

    而不是:

    do
    { ...    
    

    还请注意,您在问2个问题时使用了3个得分变量

,

此行代码将撤消您在循环期间所做的所有recyclerView.setItemAnimator(null);计算:

totalscore

由于看起来 totalscore = score1 + score2 + score3; score1score2只是临时变量,所以我想您应该摆脱这行代码。还可以考虑声明这些变量在它们所属的每个逻辑块的局部。

本文链接:https://www.f2er.com/3165630.html

大家都在问