0

我对编程有点陌生,我努力想弄清楚的问题就是这个。我的控制台应用程序询问用户他们想要输入多少测试分数来计算所有分数的平均值和总分。如果他们输入 3,它会要求他们输入 3 个测试分数,然后它会显示所有分数的平均值和总分。然后它会询问他们是要继续还是结束程序,如果他们输入yes continue,它应该从头开始。我的问题是,当我说是时,它并没有清除总分或分数,它只是从前一个继续,只是将新分数添加到其中。

 import java.util.Scanner;

 public class TestScoreApp
 {
       public static void main(String[] args)
       {
           // display operational messages
           System.out.println("Please enter test scores that range from 0 to 100.");
           System.out.println("To end the program enter 999.");
           System.out.println();  // print a blank line

           // initialize variables and create a Scanner object
           int scoreTotal = 0;
           int scoreCount = 0;
           int testScore = 0;
           Scanner sc = new Scanner(System.in);
           String choice = "y";

           // get a series of test scores from the user
           while (!choice.equalsIgnoreCase("n"))
           {
               System.out.println("Enter the number of test score to be entered: ");
               int numberOfTestScores = sc.nextInt();

               for (int i = 1; i <= numberOfTestScores; i++)
               {
                    // get the input from the user
                    System.out.print("Enter score " + i + ": ");
                    testScore = sc.nextInt();

                    // accumulate score count and score total
                    if (testScore <= 100)
                    {
                         scoreCount = scoreCount + 1;
                         scoreTotal = scoreTotal + testScore;
                    }
                    else if (testScore != 999)
                          System.out.println("Invalid entry, not counted");


                }
                double averageScore = scoreTotal / scoreCount;
                String message = "\n" +
                     "Score count:   " + scoreCount + "\n"
                   + "Score total:   " + scoreTotal + "\n"
                   + "Average score: " + averageScore + "\n";
                System.out.println(message);
                System.out.println();
                System.out.println("Enter more test scores? (y/n)");
                choice= sc.next();
          }



    // display the score count, score total, and average score



    }
}
4

2 回答 2

1

只需在 while 循环开始后移动分数变量声明:

// create a Scanner object
Scanner sc = new Scanner(System.in);
String choice = "y";

// get a series of test scores from the user
while (!choice.equalsIgnoreCase("n"))
{
    // initialize variables
    int scoreTotal = 0;
    int scoreCount = 0;
    int testScore = 0;

    System.out.println("Enter the number of test score to be entered: ");
    int numberOfTestScores = sc.nextInt();

这样,每次进程再次开始时,它们将被初始化为 0。

于 2013-02-06T00:53:02.043 回答
1

while 循环中的第一条语句应该将 scoreTotal 和 scoreCount 设置为 0。

于 2013-02-06T00:53:39.443 回答