首页 > 解决方案 > 允许变量影响循环中的语句数

问题描述

有没有办法让“testscore”变量影响 do while 循环中的语句数?就像如果说 testscore = 4,我最多可以有 score4,它将被包含在计算中。

import javax.swing.JOptionPane;

public class Task4 {
    public static void main(String[] arges) {

        double nof=1;
        double testscore;
        double score1;
        double score2;
        double score3;
        double averagescore;
        double x=11;
        String input;

        input=JOptionPane.showInputDialog("How many students do you have?");
        nof = Double.parseDouble(input);

        input=JOptionPane.showInputDialog("How many test scores per student?");
        testscore=Double.parseDouble(input);

        do {
          input=JOptionPane.showInputDialog("Enter score 1");
          score1= Double.parseDouble(input);

          input=JOptionPane.showInputDialog("Enter score 2");
          score2 = Double.parseDouble(input);

          input=JOptionPane.showInputDialog("Enter score 3");
          score3=Double.parseDouble(input);

          averagescore = (score1 + score2 + score3)/testscore;

          JOptionPane.showMessageDialog(null, "The student's average test score is " + averagescore);
          x++;

        } while (x <= nof);
    }
}

标签: javaeclipse

解决方案


是的,您可以使用 for 循环来收集分数。如果您只使用分数来计算平均值,那么您可以保留一个运行总计。如果您需要更多的分数,您可以创建一个double[] scores = new double[testscores];变量来在读取它们时存储它们。

public static void main(String[] arges) {

    int nof = 1; // this should be an int since you can't have a partial student
    int testscore;  // also an int since you can't have a partial test
    String input;

    input = JOptionPane.showInputDialog("How many students do you have?");
    nof = Integer.parseInt(input);

    input = JOptionPane.showInputDialog("How many test scores per student?");
    testscore = Integer.parseInt(input);

    for (int num = 1; num <= nof; num++) {
        double total = 0;
        for (int i = 0; i < testscore; i++) {
            input = JOptionPane.showInputDialog("Student #" + num + ": Enter score " + i);
            total += Double.parseDouble(input);
        }

        double averagescore = total / testscore;

        JOptionPane.showMessageDialog(null, "Student " + num + "'s average test score is " + averagescore);
    }
}

推荐阅读