简体   繁体   中英

Explain println and print statement after a loop has been executed in Java?

What happens here, that is when print is used, why will it not print where the line stops?

for(int i = 0; i <=2; i++){
System.out.println(i)
System.out.print("s");
}

Why will it not print the s after 2 like this:

0

1

2s

From what i learnt, someone said it will buffer for ever? What does that mean? The computer will know to print the letter s beside 2 because it has stopped there, so why not print?

You are missing a semi-colon after the first statement in your loop.

for (int i = 0; i <=2; i++) {
    System.out.println(i);
    System.out.print("s");
}

The above code will output this:

0
s1
s2
s

However if you do this:

for (int i = 0; i <=2; i++) {
    System.out.print(i);
    System.out.println("s");
}

Which will print the following:

0s
1s
2s

With an extra line break at the end.

For each iteration in the loop, the code prints the integer, adds a newline (since println is used) and prints the s. So you will have an output like

0

s1

s2

s

What happens with you code:

0
s1 
s2
s

Why it happens: if you use

print("s");

the program will print "s" and thats it. if you use:

println("s");

you'll get a new line after each "s" which I suppose is what you seek.

这是因为println将在语句的末尾而不是语句的开头保留换行符(\\ n)。

Actually print prints the s where the line stops!. The problem here is, println already put a new line first, and then print starts from that place.

Both statements are in the same loop so will run one after another.

So:

System.out.println(i);   

will give i(whatever that variable is) then a new line.

System.out.print("s");   

will print "s". With no new line.

Your output will be

0
s1
s2
s

And since your only want an output on the last iteration of the loop, you need an 'if':

    for (int i = 0; i <= 2; i++) {
        System.out.print(i);
        if (i == 2) {
        System.out.print("s");
        } else {
        System.out.println("");
        }
    }

Which gives:

0
1
2s

The actual answer is that the previous println already puts it to the next line. Using System.out.print("s") actually goes horizontally forever, therefore it never prints.

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