您好我对Java及其所有奇迹都很陌生。当谈到while循环和for循环时,我完全糊涂了。我很难让我的代码仅为实数打印n个用户输入的平均值,然后计算平均值并获得所用输入的高值和低值。如果用户输入"结束"停止并计算....我只使用了java也许2周了,我的努力工作,我试图学习但是循环很难让我听到...这里是我的代码到目前为止。
int inputNumber = Integer.parseInt (JOptionPane.showInputDialog("Enter a few real numbers"));
//number entered by user
while (inputNumber !=0) {//numbers entered
sum += inputNumber;
count++;//adds one to count for every number entered
if (count == 7){
System.out.println("thats enough numbers enter end");
//stops excess of seven numbers prompts type end to finish
}
else {
average = ((double)sum) / count;//gets average double the numbers divided by number of numbers
System.out.println("average:"+ average); //displays average
JOptionPane.showMessageDialog(null, "The average is " +average + "and the number of numbers entered is " + count);
}
}
答案 0 :(得分:0)
你可以从用户那里获得循环外的输入数量,迭代总次数以获得输入和总和,计算平均值一旦计算出来
int total = Integer.parseInt(JOptionPane.showInputDialog("Enter total number of inputs "));
for (int i = 0; i < total; i++) {
sum += Integer.parseInt(JOptionPane.showInputDialog("Enter input number "));
}
average = sum / total;
JOptionPane.showMessageDialog(null, "The average is " + average + "and the number of numbers entered is " + total);
答案 1 :(得分:0)
我试着写一个,希望它有所帮助。我也是Java的新手。
int sum = 0;
int count = 0;
double average = 0;
int inputNumber2 = 0;
//number entered by user
while (inputNumber2 == 0) {//numbers entered
int inputNumber = Integer.parseInt (JOptionPane.showInputDialog("Enter a few real numbers"));
sum += inputNumber;
count++;//adds one to count for every number entered
if (count == 7) {
// System.out.println("thats enough numbers enter end");
//stops excess of seven numbers prompts type end to finish
String text3 = JOptionPane.showInputDialog("Thats enough numbers enter end");
break;
} else {
average = ((double) sum) / ((double)count);//gets average double the numbers divided by number of numbers
System.out.println("average:" + average); //displays average
JOptionPane.showMessageDialog(null, "The average is " + average + "and the number of numbers entered is " + count);
}
}
}