计算正确的分数

时间:2015-07-30 07:40:51

标签: java if-statement

我被赋予了一个分配问题的任务,然后在最后计算总分。这是我的代码。 TIA

    Scanner userInput = new Scanner(System.in);
    int userAnswer;

    System.out.print("Q1.) Who is the main character in the Legend of Zelda?\n"
            + "1.) Link\n2.) Princess Zelda\n3.)Super Mario"
            + "\nAnswer: ");
    userAnswer = userInput.nextInt();
    if (userAnswer == 1){
        System.out.print("That is correct! ");
    }
    else {
        System.out.print("I'm sorry but that is wrong.");
    }

    System.out.print("\nQ2.) Who is the main character in the Naruto?\n"
            + "1.) Sasuke\n2.) Naruto\n3.) Sakura"
            + "\nAnswer: ");
    userAnswer = userInput.nextInt();
    if (userAnswer == 2){
        System.out.print("That is correct! ");
    }
    else {
        System.out.print("I'm sorry but that is wrong.");
    }

    System.out.print("Q3.) Who is the main character in the Dragon Balls??\n"
            + "1.) Krillin\n2.) Bulma\n3.) Goku"
            + "\nAnswer: ");
    userAnswer = userInput.nextInt();
    if (userAnswer == 3){
        System.out.print("That is correct! ");
    }
    else {
        System.out.print("I'm sorry but that is wrong.");
    }

唯一的问题是,我应该添加什么声明来加总总分?

1 个答案:

答案 0 :(得分:0)

你需要一个变量来保持分数,并在每次答案正确时增加:

Scanner userInput = new Scanner(System.in);
int userAnswer;
int totalScore = 0;

System.out.print("Q1.) Who is the main character in the Legend of Zelda?\n"
        + "1.) Link\n2.) Princess Zelda\n3.)Super Mario"
        + "\nAnswer: ");
userAnswer = userInput.nextInt();
if (userAnswer == 1){
    System.out.print("That is correct! ");
    totalScore = totalScore + 1;  // or totalScore++
}
else {
    System.out.print("I'm sorry but that is wrong.");
}

System.out.print("\nQ2.) Who is the main character in the Naruto?\n"
        + "1.) Sasuke\n2.) Naruto\n3.) Sakura"
        + "\nAnswer: ");
userAnswer = userInput.nextInt();
if (userAnswer == 2){
    System.out.print("That is correct! ");
    totalScore = totalScore + 1;  // or totalScore++
}
else {
    System.out.print("I'm sorry but that is wrong.");
}

System.out.print("Q3.) Who is the main character in the Dragon Balls??\n"
        + "1.) Krillin\n2.) Bulma\n3.) Goku"
        + "\nAnswer: ");
userAnswer = userInput.nextInt();
if (userAnswer == 3){
    System.out.print("That is correct! ");
    totalScore = totalScore + 1;  // or totalScore++
}
else {
    System.out.print("I'm sorry but that is wrong.");
}

System.out.print("your total score is " + totalScore);