2 回答
TA贡献1772条经验 获得超8个赞
问题是你没有跳出内循环。在这里我将如何编写相同的代码:
import java.util.ArrayList;
import java.util.Scanner;
public class ReadNumbers {
public static void main(String[] args) {
ArrayList<Integer> inputs = new ArrayList<Integer>();
System.out.println("Enter some numbers: ");
try (Scanner scnr = new Scanner(System.in)) {
do {
inputs.add(scnr.nextInt());
System.out.println("Would you like to enter another y/n?");
} while (scnr.next().equalsIgnoreCase("y"));
}
System.out.println(inputs);
}
}
这会产生以下输出:
Enter some numbers:
14
Would you like to enter another y/n?
y
15
Would you like to enter another y/n?
y
17
Would you like to enter another y/n?
y
44
Would you like to enter another y/n?
n
[14, 15, 17, 44]
读取数字的另一种方法是从空格分隔的行中读取几个:
TA贡献1852条经验 获得超7个赞
我认为你把这个复杂化了。您只需要一个循环,该循环一直运行到用户输入“n”为止。
在此之前,要求用户输入一个数字,读入,然后询问他们是否要继续。适当地更新循环条件,你就完成了:
public static void main(String... args) {
ArrayList<Integer> inputs = new ArrayList<Integer>();
try (Scanner scnr = new Scanner(System.in)) {
boolean valid = true;
while (valid) {
System.out.println("Enter some numbers: ");
if (scnr.hasNextInt()) {
inputs.add(scnr.nextInt());
}
System.out.println("Would you like to enter another?");
String response = scnr.next();
valid = response.trim().equalsIgnoreCase("y");
}
}
System.out.println(inputs);
}
产生输出
Enter some numbers:
1
Would you like to enter another?
y
Enter some numbers:
2
Would you like to enter another?
y
Enter some numbers:
3
Would you like to enter another?
n
[1, 2, 3]
添加回答
举报