简体   繁体   中英

Can someone help me understand why I need an IF and WHILE for this answer?

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

the only deference is in the first code

if(input.hasNext())
    System.out.print(input.nextLine());
    while (input.hasNext()){
        System.out.print(" " + input.nextLine());
    }
}

you will print " " -space- then the string, but in the second one, you will start from the start of the line then it will put space between the words so

"space" first second third

is deferent from

first second third // without space at first

A common problem encountered when creating a String with separators from a collection is how to avoid a surplus leading or trailing space. This is what the extra if-statement achieves. There are several other ways to solve this, below I provide two alternatives.

You could also do this:

// first build the output string using a StringBuilder
StringBuilder sb = new StringBuilder();
while(input.hasNext()) {
    sb.append(input.nextLine()).append(" ");      
}    
// if there was input, the StringBuilder will have an extra space at the end
if (sb.length() > 0) {
    // in that case remove the space and print the result
    sb.deleteCharAt(sb.length() - 1);
    System.out.println(sb);
}

Or for even more fun, a recursive solution:

private String read(Scanner input) {
    if (!input.hasNext()) {
        return "";
    }
    String head = input.nextLine();
    if (input.hasNext()) {            
        return head + " " + read(input);
    }
    else {
        return head;
    }
}

The problem is that the output would start with a space. You could just put the space at the end and it would work fine:

System.out.print(input.nextLine() + " ");

If this still causes a problem, maybe this will work:

while(input.hasNext()){
    System.out.print(input.nextLine());

    if(input.hasNext())
        System.out.print(" ");
}

I haven't tested it, but it should append a space to every line except the last one.

Here's another way to do it (I can't find where I originally saw a similar usage):

String spacer = "";
while(input.hasNext()){
    System.out.print(spacer + input.nextLine());
    spacer = " ";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM