对编程有点新意,我努力想弄清楚的问题就是这个问题。我的控制台应用程序询问用户他们想要输入多少测试分数,以计算所有分数的平均值和总数。如果他们输入3,则要求他们输入3个测试分数,然后显示所有分数的平均值和总数。它然后问他们他们想要继续或结束程序,如果他们输入是继续它应该从头开始。我的问题是,当我说是,它不能清除它只是从前一个继续的总数或分数,只是将新分数添加到那个。
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
}
}
答案 0 :(得分: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.
答案 1 :(得分:1)
while循环内的第一个语句应将scoreTotal和scoreCount设置为0。