Monday 27 March 2017

java - How to read in an entire string after reading in integer and double?




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?


Answer



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();

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...