如何制作一个数字列表来计算余数的算术平均值?

我有一个关于java的项目,它希望我编写一个控制台程序,在一行中读取数字分数列表,用空格分隔,丢弃最高和最低数字,然后计算余数的算术平均值。

我有关于如何制作数字列表来计算算术平均值的问题。

这些是代码:

实际上这些代码在Java Applet和Java Application中工作,但我可以使用扫描仪方法获取数字,但我找不到解决方法来为数字制作列表。

public static void main(String[] args) { /* * For data input. */ Scanner kb = new Scanner(System.in); /* * Declare an array to store the judge's scores. */ double[] scores = new double[8]; /* * Declare variables for lowest and highest scores. */ double lowestScore = Integer.MAX_VALUE; double highestScore = Integer.MIN_VALUE; /* * Read 7 judge's scores. */ for (int i = 0; i < 7; i++) { System.out.println(String.format("Judge Score #%d: ", i + 1)); scores[i] = kb.nextDouble(); /* * Compare the current score with the lowest and the highest scores. */ if (scores[i]  highestScore) { highestScore = scores[i]; } } /* * Sum the scores, except the lowest and the highest scores. */ double total = 0.00; for (int i = 0; i < 7; i++) { if (scores[i] != lowestScore && scores[i] != highestScore) { total = total + scores[i]; } } /* * Display the output. */ DecimalFormat df = new DecimalFormat("0.00"); System.out.println("Total points received: " + df.format(total)); System.out.println("Arithmetic Mean : " + df.format(total / 7)); } 

有没有人对我的问题有其他想法?

实际上,从数组中删除最低和最高数字的最简单方法是执行以下操作:

 Arrays.sort(names); 

然后丢弃第0th element7th element或以某种方式从数组中删除它们。

 /* * Read 7 judge's scores. */ for (int i = 0; i < 7; i++) { System.out.println(String.format("Judge Score #%d: ", i + 1)); scores[i] = kb.nextDouble(); } Array.sort(scores); /* * Sum the scores, except the lowest and the highest scores. */ double total = 0.00; for (int i = 1; i < 6; i++) { total = total + scores[i]; } 

阅读完分数后,您只需要几行:

 Arrays.sort(scores); double total = 0; for (double score : Arrays.copyOfRange(scores, 1, 6)) total += score; double average = total / 6; 

请注意,无需知道最高/最低分数是多少 ,因此所有与此相关的代码或与此无关,应删除。 此外,不需要保留对子数组的引用,只需对其进行迭代,因此为了简洁起见,在foreach循环中使用Arrays.copyOfRange()的结果。


当整合到您的程序中时,您的整个方法可能会缩减为以下内容:

 public static void main(String[] args) { Scanner kb = new Scanner(System.in); double[] scores = new double[8]; for (int i = 0; i < 7; i++) { System.out.println(String.format("Judge Score #%d: ", i + 1)); scores[i] = kb.nextDouble(); } Arrays.sort(scores); double total = 0.00; for (double score : Arrays.copyOfRange(scores, 1, 6)) total += score; DecimalFormat df = new DecimalFormat("0.00"); System.out.println("Total points received: " + df.format(total)); System.out.println("Arithmetic Mean : " + df.format(total / 6)); } 

另请注意,您有一个算术错误:总数应除以6以找到平均值,而不是7,因为总计有6个得分(两个极值得分减少8个)。