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