使用for循环获取一定数量的输入?

时间:2013-11-30 06:47:33

标签: java joptionpane

*强调文本*我正在尝试编写一个程序来收集用户的测试和测试分数,对其进行平均,然后返回测试次数,每个测试分数,平均值以及与之对应的字母等级平均。

int tests = Integer.parseInt(JOptionPane.showInputDialog(null,
            "Input the number of tests you want to average.", "ClassGrader",
            JOptionPane.INFORMATION_MESSAGE));
    while (tests <= 0) {
        tests = Integer.parseInt(JOptionPane.showInputDialog(null,
                "That is an invalid input.\nTry again.", "ClassGrader",
                JOptionPane.ERROR_MESSAGE));
    }
    for (int runs = 0; runs <= tests; runs++) {

    }

我想知道如何为用户提供与用户测试分数相同数量的输入选项。

我认为实现这一目标的最佳方法是使用for语句,尽管我不知道什么是块语句的好用。

当最终对话框显示输入的所有信息时,如何为用户提供正确数量的输入选项,然后才能调用每个测试分数

1 个答案:

答案 0 :(得分:0)

要计算平均值,您需要输入sum并计算输入数字。看一下示例代码,

int tests = Integer.parseInt(JOptionPane.showInputDialog(null,
        "Input the number of tests you want to average.", "ClassGrader",
        JOptionPane.INFORMATION_MESSAGE));

int sum=0;
int count=0;
while (tests-- >0) {
   int num = Integer.parseInt(JOptionPane.showInputDialog(null,
        "Input the number ", "ClassGrader",
        JOptionPane.INFORMATION_MESSAGE);
    if(num<=0){
      JOptionPane.showMessageDialog(null,
            "That is an invalid input.\nTry again.", "ClassGrader",
            JOptionPane.ERROR_MESSAGE));
      tests++; // To skip the count of invalid number.
    }
    else{
     sum += num;
     count++;
    }
  }

  double average=(double)sum/count;