如何按Enter退出while循环?

时间:2016-02-22 21:37:50

标签: java input enter

我试图通过按键盘上的 Enter 键来获得一个while循环。我的代码是:

package javaapplication4;
import java.util.ArrayList;
import java.util.Scanner;

public class JavaApplication4 {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        ArrayList<Double> numbers = new ArrayList( );
        while (true) {
            System.out.println("Please enter the numbers seperated by a space: ");
            numbers.add(keyboard.nextDouble());
           //want the while loop to break here by pressing "enter" after entering array values
        }
        System.out.println(numbers);
    }

3 个答案:

答案 0 :(得分:2)

不要使用循环来获取输入,或nextDouble。你真正想要的是一行输入,然后你将它分成一个双打列表。因此,使用nextLine,拆分它,并解析每个项目。像这样:

Scanner keyboard = new Scanner(System.in);
ArrayList<Double> numbers = new ArrayList( );
String input = keyboard.nextLine();
for(String item : input.split(" ")){
    numbers.add(Double.parseDouble(item));
}

这忽略了任何类型的输入验证,但它显示了一种通用的方法。

这样做是因为一旦你点击&#34;输入&#34;,就会结束第一行,这意味着扫描程序可以移过nextLine进入你的大部分代码。由于您从不尝试阅读任何其他内容,因此它不会阻止等待任何更多输入,并且一旦完成就可以成功退出。

答案 1 :(得分:1)

我自己喜欢使用try {...} catch(NumberFormatException),所以当你得到一个空白行(即输入)时,你的catch块被激活,你已经逃脱了循环

try {
    while (true) {
      System.out.println("Please enter the numbers seperated by a space: ");
      numbers.add(keyboard.nextDouble());
      //want the while loop to break here by pressing "enter" after entering array values
    }
} catch (NumberFormatException ex) {}
System.out.println(numbers);

答案 2 :(得分:1)

import java.util.ArrayList;
import java.util.Scanner;
import java.util.StringTokenizer;

public class JavaApplication4 {

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        ArrayList<Double> numbers = new ArrayList();
        System.out.println("Please enter the numbers seperated by a space: ");

        String line = keyboard.nextLine();
        StringTokenizer token = new StringTokenizer(line, " ");
        while(token.hasMoreTokens()) {
            numbers.add(Double.parseDouble(token.nextToken()));
        }

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

    }

}