Java input string

I'm having difficulty returning a user input string. If I have a code:

System.out.println("please enter a digit: "); number1 = in.nextInt(); System.out.println("enter another digit: "); number2 = in.nextInt(); System.out.println("enter a string: "); string = in.nextLine(); //calculations System.out.println(number1); System.out.println(number2); System.out.println(string); 

it prints numbers, but not a string. I feel that the solution is very simple, but now I have a brain fart. Any help would be appreciated!

+4
source share
4 answers

You need to call an additional in.nextLine() before calling in.nextLine() to read in a line. It must consume an additional new line symbol.

As an explanation, you can use this input as an example:

 23[Enter] 43[Enter] Somestring[Enter] 

(23 and 43 can be just any number, the important part is a new line )

You need to call in.nextLine() to use the new line from the previous in.nextInt() , especially the new line character after 43 in the above example.

nextInt() will consume as many digits as possible and stop when the next character is not a digit, so a new line appears. nextLine() will read everything until it encounters a new line. To do this, you will need an additional nextLine() to delete the new line after 43 , so you can continue reading Somestring on the next line.

If, for example, your input looks like this:

 23 43 Somestring[Enter] 

You do not press Enter and just keep typing, then your current code will show a line (which will be Somestring , notice a space), because after 43 there is no new line that prevents it.

+8
source

Line

 int number2 = in.nextInt(); 

passes a string to a statement

 string = in.nextLine(); 

when you enter the number and press ENTER. Using this line with Scanner.nextLine() , before trying to read another, will fix the problem:

 ... number2 = in.nextInt(); in.nextLine(); System.out.println("enter a string: "); string = in.nextLine(); ... 
+4
source

In your case, in.next() will be enough to read the line if there is no space between them.

+1
source

String xxx;

Scanner Number 1 = New Scanner (System.in)

xxx = number1.nextLine ();

+1
source

Source: https://habr.com/ru/post/1435766/


All Articles