4

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!

Ryan Sayles
  • 3,389
  • 11
  • 56
  • 79
  • 1
    You need a in.nextLine() before calling in.nextLine() to read in the string. It is to consume the new line character from the previous line where you read integer. – nhahtdh Sep 23 '12 at 14:44
  • @nhahtdh: you should post this as an answer. – JB Nizet Sep 23 '12 at 14:45
  • possible duplicate of [Scanner issue when using nextLine after nextInt](http://stackoverflow.com/questions/7056749/scanner-issue-when-using-nextline-after-nextint) – Eng.Fouad Sep 23 '12 at 14:56

4 Answers4

8

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.

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
4

The line

int number2 = in.nextInt();

passes a String to the statement

string = in.nextLine();

when you type the number and press ENTER. Consuming this string using Scanner.nextLine() before attempting to read another will fix the problem:

...
number2 = in.nextInt();
in.nextLine();
System.out.println("enter a string: ");
string = in.nextLine();
...
Reimeus
  • 158,255
  • 15
  • 216
  • 276
1

In your case in.next() would be sufficient to read the string if there is no space in between.

basiljames
  • 4,777
  • 4
  • 24
  • 41
1

String xxx;

Scanner number1 = new Scanner(System.in)

xxx = number1.nextLine();

DRastislav
  • 1,892
  • 3
  • 26
  • 40