Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java input string

Tags:

java

I'm having difficulties 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 out the numbers but not the string. I feel like the solution is very simple but I'm having a brain fart right now. Any help would be appreciated!

like image 741
Ryan Sayles Avatar asked Dec 09 '22 20:12

Ryan Sayles


1 Answers

You need to call an extra in.nextLine() before calling in.nextLine() to read in the string. It is to consume the extra new line character.

As for explanation, let's use this input as example:

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

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

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

nextInt() will consume as many digits as possible and stop when the next character is a non-digit, so the new line is there. nextLine() will read everything until it encounters a new line. That's why you need an extra nextLine() to remove the new line after 43, so that you can proceed to read the Somestring on the next line.

If, for example, your input is like this:

23 43 Somestring[Enter]

You don't press Enter and just continue to type, then your current code will show the string (which will be  Somestring, note the space) since there is no new line obstructing after 43.

like image 61
nhahtdh Avatar answered Dec 31 '22 11:12

nhahtdh