How do I exit a while loop by pressing enter?

前端 未结 3 374
感情败类
感情败类 2021-01-16 13:55

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         


        
相关标签:
3条回答
  • 2021-01-16 14:27

    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);
    
    0 讨论(0)
  • 2021-01-16 14:33

    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.

    0 讨论(0)
  • 2021-01-16 14:38
    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);
    
        }
    

    }

    0 讨论(0)
提交回复
热议问题