允许变量影响循环中的语句数



有没有办法允许"testscore"变量影响do while循环中的语句数量?就像说测试核心= 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);
}
}

是的,您可以使用 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);
}
}

最新更新