0

So I have the following inputs:

3
3.0
How are you doing

And I need to store them to the following variables:

int myInt
double myDouble
String myString

Here is what I've tried:

myInt = scan.nextInt();
myDouble = scan.nextDouble();
myString = scan.nextLine();

That works for the Integer and Double value but the String gave me a NULL value.

Then I tried this:

myInt = scan.nextInt();
myDouble = scan.nextDouble();
myString = scan.next();

Again it worked for the first two, but the string only holds the first word. How can I read the entire string? Do I need to setup a loop?

Mamun
  • 58,653
  • 9
  • 33
  • 46
Fortuna Iwasaki
  • 141
  • 1
  • 10

3 Answers3

10

nextLine() is a bit confusingly named. It doesn't give you the next line, but reads up until the next line break it encounters.

After you've called nextDouble(), the scanner is positioned after the 3.0 but before the new line, so nextLine() reads to the end of that line and gives you an empty result.

You could either use skip(String) to skip the newline after 3.0, or just call nextLine() once and throw it away:

myInt = scan.nextInt();
myDouble = scan.nextDouble();
scan.nextLine(); // Skip the remainder of the double line
myString = scan.nextLine();
Chris
  • 10,017
  • 1
  • 36
  • 45
0
myInt = scan.nextInt();
myDouble = scan.nextDouble();

instead of using scanner to give you the double and int use nextLine() and cast it manually. scanner is not going to the next line that's the problem.

 myInt = Integer.parseInt(scan.nextLine());
 myDouble = Double.parseDouble(scan.nextLine());
 myString = scan.nextLine();
Priyamal
  • 2,747
  • 1
  • 17
  • 44
  • This is the best way to handle input. It allows you to validate the input and tell the user if they entered something wrong, rather than letting the program crash. – 4castle May 23 '16 at 21:00
  • @4castle thanks for the comment. – Priyamal May 24 '16 at 07:29
0

When you call nextDouble method it reads a double value and advances the scanner accordingly. So, when you call nextDouble your scanner is after the value 3.0 but before the next-line character. Now when you call nextLine() method it advances scanner until it hits the next next-line character and returns whatever was read when the advancement was made. Since your scanner is right before the next-line character, when you call nextLine() method the scanner hits next-line character immediately without reading anything. Hence your nextLine() method returns null.

If your input values are in each line you can follow the suggestion of @Priyamal or you can insert one more nextLine() method call before myString = scan.nextLine(). So, your code for getting the input will look like following:

myInt = scan.nextInt();
myDouble = scan.nextDouble();
scan.nextLine();
myString = scan.nextLine();
Bijay Regmi
  • 90
  • 14