Home  >  Article  >  Java  >  How to end the input by pressing Enter when inputting in Java

How to end the input by pressing Enter when inputting in Java

WBOY
WBOYforward
2023-04-19 14:40:163807browse

End the input by entering (enter) when inputting

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.

Solution

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

java Press Enter to end the input line

Question

How to end the input by pressing Enter when inputting in Java

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:

How to end the input by pressing Enter when inputting in Java

requires two carriage returns to end the input.

Found this solution

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

How to end the input by pressing Enter when inputting in Java

Use the string as the input stream, and spaces as separators:

Source code:

How to end the input by pressing Enter when inputting in Java

This calls the following constructor:

How to end the input by pressing Enter when inputting in Java

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!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete