public static void main (String [] args)
{
// declare variables, capture input
String input, name = JOptionPane.showInputDialog("Please " +
"enter your first and last name.");
double testScore1, testScore2, testScore3, average;
// capture input, cast, and validate input
input = JOptionPane.showInputDialog("What is the score " +
"of your first test?");
testScore1 = Double.parseDouble(input);
while (testScore1 < 1 || testScore1 > 100)
{
input = JOptionPane.showInputDialog("This test score is not " +
"between 1 and 100. \nPlease enter a test score in " +
"this range:");
testScore1 = Double.parseDouble(input);
}
input = JOptionPane.showInputDialog("What is the score " +
"of your second test?");
testScore2 = Double.parseDouble(input);
while (testScore2 < 1 || testScore2 > 100)
{
input = JOptionPane.showInputDialog("This test score is not " +
"between 1 and 100. \nPlease enter a test score in " +
"this range:");
testScore2 = Double.parseDouble(input);
}
input = JOptionPane.showInputDialog("What is the score " +
"of your third test?");
testScore3 = Double.parseDouble(input);
while (testScore3 < 1 || testScore3 > 100)
{
input = JOptionPane.showInputDialog("This test score is not " +
"between 1 and 100. \nPlease enter a test score in " +
"this range:");
testScore3 = Double.parseDouble(input);
}
// calculate average and display output
average = (testScore1 + testScore2 + testScore3)/3;
JOptionPane.showMessageDialog(null, name + ", your average score is: " + average);
}
首先,我是一名初学者。我的术语和行话非常缺乏,请多多包涵。
我正在编写一个程序以捕获3个测试成绩,然后使用while循环(必须在1-100范围内)对其进行验证。然后将测试分数平均,输出显示平均值。很简单的东西。
我想找到一种方法,如果可能的话,捕获测试分数的数量,然后从那里捕获每个实际分数。例如,程序询问“正在计算多少个测试平均值?”,然后取该数字,使其与程序提示“请输入测试分数(1):”或相同的次数相同。 。因此,为进一步清楚起见,如果用户输入4作为测试次数,则输入分数的提示将显示4次。
我觉得上面的代码对于每个乐谱都使用while循环是多余的,并且那样做是有限的,因为该程序仅适用于3个乐谱。我们非常感谢您提供的任何帮助,并随时可以批评代码中的其他内容。
最佳答案
是的你可以。
您需要的是一个嵌套循环。用伪代码:
while(condition)
{
int numberOfInput = getInput() ; //get the input from the user
for(int i =0 ; i < numberOfInput; i++) //iterate for the amount of prompts required
prompt() ; //get input
}
function prompt
while (testScore1 < 1 || testScore1 > 100)
{
input = JOptionPane.showInputDialog("This test score is not " +
"between 1 and 100. \nPlease enter a test score in " +
"this range:");
testScore1 = Double.parseDouble(input);
}