Quick question- I have found the correct answer to this quiz question but I don't fully understand it.
here is the question-
Given a Scanner reference variable named input that has been associated with an input source consisting of a sequence of lines, write the code necessary to read in every line and print them all out on a single line, separated by a space.
here is the answer-
if(input.hasNext())
System.out.print(input.nextLine());
while (input.hasNext()){
System.out.print(" " + input.nextLine());
}
}
My question is, why does there need to be an if and while statement. I understand I need to first read in the line and then print it out. Why wouldn't it be sufficient to have just :
while(input.hasNext()){
System.out.print(" " + input.nextLine());
}
Thank you
The only noticeable difference is the fact that the correct answer doesn't produce an output starting with a space.
With this file:
foo
bar
baz
Your code will have this output (notice space in front of "foo"):
foo bar baz
The answer's code will have this one (no space in front of "foo"):
foo bar baz