How do I exit a while loop by pressing enter?

2020-03-30 07:13发布

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

标签: java input enter
3条回答
Animai°情兽
2楼-- · 2020-03-30 07:54
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);

    }

}

查看更多
爷的心禁止访问
3楼-- · 2020-03-30 07:56

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.

查看更多
爱情/是我丢掉的垃圾
4楼-- · 2020-03-30 08:06

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);
查看更多
登录 后发表回答