Friday 23 August 2019

Why cannot I call nextLine() method twice in java?



While using nextInt() method of Java, I came across this code:



Scanner scan = new Scanner(System.in);

int count = scan.nextInt();
String string1 = scan.nextLine();


I know that string1 would contain an empty string. My question is why calling nextLine method twice like following gives error:



String string1 = scan.nextLine().nextLine();

Answer



Here:




String string1 = scan.nextLine().nextLine();


Lets break it up:



String string1 = scan.nextLine()


calls nextLine() on a scanner. It returns a String.




Thus, your code boils down to



String string1 = someOtherString.nextLine(); 


which, of course, can't work. Because the String class has no idea about a next line, and therefore no such method!



Remember: the scanner returns a string, and these are two very different objects.




If you take an egg out of a box, why would you expect that you can take another egg out of that egg you got?! You can take two eggs out of the same box, but not an egg out of an egg.



Finally: yes, there is the idea "fluent" APIs, that allow for chaining method calls in "such" ways. But that can only work for scenarios that are explicitly designed for exactly that.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...