How do I exit a while loop by pressing enter?

蹲街弑〆低调 提交于 2019-12-19 11:19:06

问题


I am trying to get a while loop to break by pressing the Enter key on a keyboard. My code is:

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);
    }

回答1:


Don't use a loop for getting the input, or nextDouble. What you really want is one line of input, which you then split into a list of doubles. So use nextLine, split it, and parse each item. Something like this:

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));
}

This ignores any sort of input validation, but it shows a general approach.

This will work because once you hit "enter", it ends the first line, meaning the scanner can move past the nextLine into the bulk of your code. Since you never try to read anything more, it doesn't block waiting for any more input, and can successfully exit once done.




回答2:


I myself like to use try { ... } catch (NumberFormatException) so when you get a blank line (ie enter) your catch block is activated and you've escaped the loop

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);



回答3:


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);

    }

}



来源:https://stackoverflow.com/questions/35564412/how-do-i-exit-a-while-loop-by-pressing-enter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!