要保存所有数字,您需要将它们放入数据结构中。如果条目的数量是未知的先验,那么使用List<Integer> enteredNums = new ArrayList<>(); 然后if (s != null) { enteredNums.add(Integer.parseInt(s); } 将允许您累积每个输入的数字。
然后您可以通过以下方式处理输入的数字:
for (Integer num : enteredNums) {
...
}
根据评论编辑:
OP 提出了两个问题:
- 如何保存用户输入的每一个数字?
- 如何在消息对话框中发布最高和最低数字。
现在如果跟踪 #1,从逻辑上讲 #2 可以解决,但在评论中收集实际数据似乎不太重要。
所以,这是一种不同的方法。如果主要目标是跟踪最大和最小,并且所有输入值的累积并不是真正的要求),那么创建几个变量并有条件地设置它们将起作用。在每个条目之后,更新最小、最大和(在这里,为了好玩)总和。
没有数据结构(如列表)就不可能完成#1,但假设真正的愿望是#2,那么就没有必要跟踪所有输入,只需跟踪当前最小和最大的输入。
public static void main(String[] args) {
// the smallest entered number
int smallest = 0;
// the largest entered number
int largest = 0;
// the total; since lots of ints could overflow an int, use a long; not
// completely immune to overflow, of course
long sum = 0L;
// whether it is the first entered number
boolean foundOne = false;
int n;
String s;
do {
// get an input
s = JOptionPane.showInputDialog("Skriv ett nummer");
// have to ensure not canceled; as s will be null
if (s != null) {
// parse the entered value; note this will throw an exception if
// cannot parse
n = Integer.parseInt(s);
// on the first go through, we set unconditionally; also update
// the boolean so can indicate if anything was entered
if (! foundOne) {
smallest = n;
largest = n;
foundOne = true;
}
else {
// set the smallest and the largest entered values
// the Math methods are just easier to read, but could
// be done by if statements
smallest = Math.min(smallest, n);
largest = Math.max(largest, n);
}
// add to the running total
sum += n;
}
} while (s != null && s.length() > 0);
// output the smallest, largest, total if anything entered
if (foundOne) {
// this should be a dialog, rather than just output, but that is left
// as an exercise for the reader
System.out.printf("The smallest value was %d\n", smallest);
System.out.printf("The largest value was %d\n", largest);
System.out.printf("The total of all entered values was %d\n", sum);
}
else {
System.out.println("no values were entered");
}
}
注意:未测试