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!
You need to call an extra
in.nextLine()before callingin.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 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 previousin.nextInt(), particularly the new line character after43in 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 extranextLine()to remove the new line after43, so that you can proceed to read theSomestringon the next line.If, for example, your input is like this:
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 after43.