Home > Java > javaTutorial > body text

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

WBOY
Release: 2023-04-19 14:40:16
forward
3811 people have browsed it

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());
Copy after login

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);
Copy after login

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);
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template