I’ve been working through the HackerRank problems and trying to always research a solution before asking in any communities for help. While I managed to get the current one to work, I feel there is some unnecessary code involved and that someone can teach me how to do it better, as I’d hate to pick up a bad habit just because it works.
In this lesson HackRank 30 days of Code (Day 2), we were asked to read 3 lines (an Int, a Double and a String) from Stdin and use the Scanner to read them, save them and manipulate them.
Scanner scan = new Scanner(System.in); /* Declare second integer, double, and String variables. */ int myI = scan.nextInt(); double myDouble = scan.nextDouble(); scan.nextLine(); String myString = scan.nextLine();
Scanning for the Int and Double was easy enough, but when I tried to scan for the String I ran into some issue:
A) If I used scan.next(); I got back one word instead of the full string.
B) If I used scan.nextLine(); I got back a blank line.
After some research I found someone suggesting that because I just did a scan.nextDouble(); the scan.nextLine(); was simply reading the blanks at the end of that line (which didn’t make much sense to me), and that if I added in an extra “scan.nextLine();” before declaring my string it should work.
Sure enough it did. I don’t really understand why, and it certainly doesn’t feel like this is the right way to solve this. It seems that if I had to do that frequently it would just bloat the code?
Can anyone shed some light on:
1) Why scan.nextLine(); was returning blank until I added an extra one?
2) Is there a better way to locate the string from the scan?
Advertisement
Answer
scan.nextLine() returns everything up until the next new line delimiter, or n.
So, i’m assuming the input look something like this:
1 2.5 whatever
So, this string actually has a next line delimiter between the first line and the second line. Before, when you didn’t have that extra nextLine(), your string was being assigned to an empty string, since it was consuming the next line delimiter.
The extra nextLine() was consuming the unwanted next line delimeter, so your string could be assigned to what you wanted it to be.