繁体   English   中英

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

[英]How to loop the same inputdialog in java but record each input in 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;

我试过这样的东西,但它不起作用。

您正在覆盖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;

这个怎么样:

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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM