java - 允许变量影响循环中的语句数
问题描述
有没有办法让“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);
}
}
解决方案
是的,您可以使用 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);
}
}
推荐阅读
- javascript - '\n' 在 textContent 中给出错误的 offsetHeight 时应用二进制搜索来查找需要截断文本的最大字符数
- node.js - Square-connect 缺少必需参数:idempotency_key,NodeJS
- python - sphinx 可以链接到位于 .rst 文档上方一个路径中的文档吗?
- solr - 在将完整数据集更新为 solr 之前,如何使用户无法使用 solr?
- c++ - 在库 dll 中存储和访问数据
- c - 具有不同数量参数的函数指针数组
- javascript - 如何生成有条件的随机项目?
- javascript - 将获取的对象数组传递给状态,但不使用钩子在组件中呈现
- java - Jar 文件是否需要 .class 文件才能执行
- java - 使用正则表达式从字符串中提取密码