我有两个程序:
Score.java 设置为执行以下操作:
- 从键盘上读取分数并打印他们的平均值。
- 分数将是数字,可能包括小数部分。
例如,分数可能是 8.73 或类似的分数。不同的比赛将有不同数量的评委。它会一直询问和阅读分数,直到用户输入“完成”。然后程序将打印总分、分数数和平均分。然后程序将提示用户查看是否还有更多参赛者。如果有重新开始提示分数。如果没有更多,则退出程序。”我将其设置为在您输入“N”时停止程序,并设置为在输入“Y”后将未来的条目添加到计算中。
import java.util.Scanner;
// This is the Score program
// Written by me
public class Score
{
public static void main(String args[])
{
Scanner game = new Scanner(System.in);
double num = 0.0;
double sum = 0.0;
int cnt = 0;
while (true)
{
System.out.println("Enter as many non-negative integers as you like ");
System.out.println("one at a time and I will find the average");
System.out.println("Enter done to stop entering numbers");
System.out.print("enter number: ");
String ans = game.next();
while (!ans.equals("done"))
{
num = Double.parseDouble(ans);
sum = sum + num;
cnt = cnt + 1;
System.out.print("enter number: ");
ans = game.next();
}
System.out.println(cnt);
System.out.println(sum);
System.out.println("Total Score " + sum + " count scores " + cnt + " avg score " + sum / cnt);
System.out.println("Enter another contestant (Y/N)?");
String str = game.next();
if (!str.equals("Y"))
break;
}
}
}
虽然上述过程有效,但在输入“Y”以添加更多分数后,我无法让我的第二个程序Olympic.java 正常工作。相反,它开始一个全新的平均值计算,而不是添加到以前的计算中:
import java.util.Scanner;
// This is the Olympic program
// Written by me
public class Olympic
{
public static void main(String args[])
{
Scanner game = new Scanner(System.in);
double num = 0.0;
double sum = 0.0;
int cnt = 0;
double highscore = Double.MAX_VALUE;
double lowscore = Double.MIN_VALUE;
while (true)
{
System.out.println("Enter as many non-negative integers as you like ");
System.out.println("one at a time and I will find the average");
System.out.println("Enter done to stop entering numbers");
System.out.print("enter number: ");
String ans = game.next();
lowscore = game.nextDouble();
highscore = game.nextDouble();
while (!ans.equals("done"))
{
num = Double.parseDouble(ans);
sum = (sum + num) - lowscore - highscore;
cnt = cnt + 1;
System.out.print("enter number: ");
if (num > highscore)
{
highscore = num;
}
if (num < lowscore)
{
lowscore = num;
}
ans = game.next();
}
System.out.println("Throwing out low score " + lowscore + " and high score " + highscore);
System.out.println("Total Score " + sum + " count scores " + cnt + " avg score " + sum / cnt);
System.out.println("Enter another contestant (Y/N)?");
String str = game.next();
if (!str.equals("Y"))
break;
}
}
}