How do I exit a while loop by pressing enter?

前端 未结 3 414
感情败类
感情败类 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);
    

提交回复
热议问题