When writing a java program, we want to complete the input of this line by entering the carriage return. This is a very common problem, but if We use Scanner, and when called through the nextInt() method, the input will not stop, a blank line will be printed, and then wait for you to continue entering the next number.
We can set up two Scanners. The first one reads data in row units, which is equivalent to using enter as the end character,
Then pass the read string into the second Scanner, and then process it
ArrayList<Integer> arr = new ArrayList() ; System.out.println("Enter a space separated list of numbers:"); Scanner in = new Scanner(System.in); String line = in.nextLine(); Scanner in2 = new Scanner(line); while(in2.hasNextInt()){ arr.add(in2.nextInt()); } System.out.println("The numbers were:"+arr.toString());
You only need to change functions such as nextInt or hasnextint to the function names you need to achieve different inputs. But it ends with a carriage return (enter).
Question
Found this method in the forum:
Scanner s =new Scanner(System.in); String str=""; do { str=s.nextLine(); if(s.hasNextLine()) break; }while(true); System.out.println(str);
After practice , this method does not work:
requires two carriage returns to end the input.
Scanner s= new Scanner(System.in); String str=s.nextLine(); Scanner st=new Scanner(str); ArrayList a =new ArrayList(); while(st.hasNextInt()) a.add(st.nextInt()); System.out.println(a);
Use the string as the input stream, and spaces as separators:
Source code:
This calls the following constructor:
The above is the detailed content of How to end the input by pressing Enter when inputting in Java. For more information, please follow other related articles on the PHP Chinese website!