我是编程新手,目前正在尝试解决该程序。应该有一个输入对话框,用户可以在其中输入不同的数字,直到用户按下“取消”按钮为止。
我使用do-while
循环来使输入对话框在用户每次按OK时弹出,但是如何保存用户写的每个数字?
当用户按CANCEL时,程序应显示一个消息对话框,其中应发布最高和最低编号。我当前的程序是这样的,
public class Övning5komma91 {
public static void main(String[] args) {
int knappNr;
int n;
String s;
do {
s = JOptionPane.showInputDialog("Skriv ett nummer");
n = Integer.parseInt(s);
} while (s != null && s.length() > 0);
}
}
答案 0 :(得分:0)
要保存所有数字,您需要将它们放入数据结构中。如果先验未知条目数,则先使用List<Integer> enteredNums = new ArrayList<>();
然后再使用if (s != null) { enteredNums.add(Integer.parseInt(s); }
可以累积每个输入的数字。
然后您可以通过以下方式处理输入的号码:
for (Integer num : enteredNums) {
...
}
根据评论进行编辑:
OP提出了两个问题:
- 如何保存用户写的每个数字?
- 应如何发布最高和最低编号的消息对话框。
现在逻辑上讲,如果一个跟踪#1就可以解决#2,但是在注释中,收集实际数据似乎不太重要。
因此,这是另一种方法。如果主要目标是跟踪最大和最小,并且实际上并不需要所有输入值的累加),那么创建几个变量并有条件地设置它们将起作用。每次输入后,更新最小,最大和(此处为好玩)总和。
没有数据结构(如List),就不可能完成#1,但是假设真正的愿望是#2,那么就不必跟踪所有输入,只需跟踪当前的最小和最大输入即可。 / p>
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");
}
}
注意:未经测试