Omkant Parashetty wrote:Note: If I uncomment line num 9 it works fine !! can you please give some inputs on this.
I'm probably the wrong person to answer this, since I dislike Scanner intensely; but it has something to do with "consuming the newline".
I presume that after you enter each string, you press the ENTER key. Well (I think), the first nextLine() consumes the newline for the first string you entered, and the second one reads the second string AND the newline, leaving the Scanner ready to read the third string.
Personally, I find it all very counter-intuitive - and actually contrary to the docs for next() (but maybe I'm misinterpreting them) - which is why I generally just use nextLine() to get stuff. But, as I say, I'm not a big fan of Scanner.
I'm sure Campbell will be along to correct me if I'm wrong. He usually is...
"Leadership is nature's way of removing morons from the productive flow" - Dogbert
Articles by Winston can be found here
Winston is right; it has to do with the line end characters. Look what it says in your book about nextLine and tell us. I am 99% sure it will be wrong.
You can find the explanation here. The simplest answer is to call nextLine() twice, discarding the first return value.That depends on your pushing the enter key after entering the number and will go horrible wrong if you try to enter all this as one line:-
123 Campbell Ritchie
You can write a loop which tests the length of the line, and there is an example here. You probably ought to create a utility class for that sort of method, so you can write
Beware: You must read the whole of the thread after the second link because there is a dangerous mistake somewhere.
Omkant Parashetty wrote:
Can some one please explain why we are not able to read second string in this program.
Your first next() method returns the next token that is delimited by whitespace (default). If your first input is "A B C<cr>", then s1 is assigned "A" and "B C<cr>" is still in the input buffer.
When nextLine() executes, it takes the remaining line (up to the line separator) from the input buffer and assigns it to s2. So s2 has " B C". The nextLine() method additionally consumes the trailing line separator and advances the position to the beginning of the next line. Note that the user does not have the opportunity to input a value for s2 because the Scanner must consume the leftover characters in the input buffer first.
When the next next() method executes, it again returns the next token delimited by whitespace. There are no characters in the input buffer and the position is on the next line. If your input is again "A B C<cr>", "A" is assigned to s3. "B C<cr>" is again left in the input buffer.
The final next() statement assigns the next token "B" to decider. "C<cr>" is left in the buffer.