如何在java中循环相同的输入对话框但是在java中记录每个输入?

时间:2014-10-26 23:48:20

标签: java

如何循环播放相同的JOptionPane.showInputDialog问题但记录输入的答案并在循环外显示总数?

例如:

for(int i=1; i<=10; i++) {

    test = JOptionPane.showInputDialog(null, "nr "+ i +": enter number");
}
total = Integer.parseInt(test);
JOptionPane.showMessageDialog(null, "total: " + total);
return;

我试过这样的事情,但它没有用。

2 个答案:

答案 0 :(得分:2)

您正在覆盖test的值,只需将其添加到上一个值即可。 因此,将您的代码更改为:

for(int i=1; i<=10; i++) {
test = JOptionPane.showInputDialog(null, "nr "+ i +": enter number");
total += Integer.parseInt(test);
    }
JOptionPane.showMessageDialog(null, "total: " + total);
return;

答案 1 :(得分:1)

这个怎么样:

int sum = 0;
//While there is nothing wrong with starting on 1 you should get used to zero index
for (int i = 0; i < 10; i++) {
   try {
      sum += Integer.parseInt(JOptionPane.showInputDialog(null, "nr "+ i +": enter number"));
   }
   catch (NumberFormatException e) {
      e.printStackTrace();
   }
}
JOptionPane.showMessageDialog(null, "total: " + sum);