[英]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.