如何退出此循环?

时间:2014-05-06 06:45:24

标签: java loops arraylist

我想按Enter键退出循环。这该怎么做?现在,当我输入任何非数字值时,循环退出,然后按Enter键。如何通过输入任何内容退出并按Enter键?

ArrayList<Integer> numbers = new ArrayList<Integer>();
int numberIn;
Scanner scan = new Scanner(System.in);
System.out.println("Enter numbers!");

while (scan.hasNextInt()) {
    numberIn = scan.nextInt();
    numbers.add(numberIn);
}

System.out.println("Numbers: " + numbers + ".");

3 个答案:

答案 0 :(得分:1)

尝试hasNext()

while (scan.hasNext("\\d+")) {
    numberIn = scan.nextInt();
    numbers.add(numberIn);
}

答案 1 :(得分:0)

ArrayList<Integer> numbers = new ArrayList<Integer>();
int numberIn;
Scanner scan = new Scanner(System.in);
System.out.println("Enter numbers!");

String input;
while (!(input = scan.nextLine()).isEmpty()) {
    numberIn = Integer.parseInt(input);
    numbers.add(numberIn);
}

System.out.println("Numbers: " + numbers + ".");

答案 2 :(得分:0)

这对我有用:

ArrayList<Integer> numbers = new ArrayList<Integer>();
int numberIn;
Scanner scan = new Scanner(System.in);
System.out.println("Enter numbers!");

String input;
while (!(input = scan.nextLine()).isEmpty()) {
    numberIn = Integer.parseInt(input);
    numbers.add(numberIn);
}

System.out.println("Numbers: " + numbers + ".");