0

我在尝试获得平均分数时遇到问题。你能帮我修复这段代码吗?

import javax.swing.*;
public class ProgrammingExercise6b{
 public static void main(String[] args){
  String input = "";
  int score = 0;
  int count = 0;
  int sum = 0;

  do {
   count++;
   input = JOptionPane.showInputDialog("Please enter the grades:");
   score = Integer.parseInt(input);

   if (score == -1) {
    sum += score;
    JOptionPane.showMessageDialog(null, "The average is: " + (score / count));
    break;
   } else {
    continue;
   }


  } while (true);
 } //main
}

我需要帮助来了解如何将所有数字相加并将它们除以数字的数量以获得平均值。

4

3 回答 3

0

移动sum += score;count++其他部分,continue;在行之前。在计算最终结果中也使用 sum。您更新的代码应如下所示

    String input;
    int score ;
    int count = 0;
    int sum = 0;

    do {
        input = JOptionPane.showInputDialog("Please enter the grades:");
        score = Integer.parseInt(input);

        if (score == -1) {
            JOptionPane.showMessageDialog(null, "The average is: " + (sum / count));
            break;
        } else {
            sum += score;
            count++;
            continue;
        }
    } while (true);
于 2018-10-29T21:32:18.937 回答
0

对于分数,您应该将它们存储在 ArrayListList<Integer> scoresList= new ArrayList<Integer>();

要添加到您使用的 arrayList

scoresList.add(yourScore);

有一个单独的整数“scoresSum”,它是你的分数的总和。要获得总和,您遍历列表。像这样的东西

    for(int score: scoresList)
{
   scoresSum += score;
}

最后有一个可变的平均值,它等于平均值

int average = scoresSum/scoresList.size();

还因为您要检查分数不是-1。检查值不等于 -1 后,将分数添加到 ArrayList

于 2018-10-29T21:42:11.007 回答
0

这看起来很像家庭作业,我首先建议你复习一下你的数学。在编写任何代码之前,您需要了解如何计算平均值。

例如,为了计算平均值,它将是总和除以总计数,从逻辑上讲,您应该只在总和更新时增加计数(添加分数)。

希望这会为您指明正确的方向。在正确编写解决方案之前,您必须了解如何解决问题。

于 2018-10-29T22:57:20.423 回答