简体   繁体   中英

System.out.println , System.err.println

I have this code:

 System.err.print("number of terms =   ");
 System.out.println(allTerms.size());
 System.err.print("number of documents =   ");
 System.out.print("number of documents =   ");

I think the results should be as this:

number of terms = 10
number of documents =1000

but the results was

10
1000
number of terms =   number of documents =

Why, and how to solve it?

The streams out and err are independent.

To get the desired output you must flush the streams or just use just one stream for all outputting.

To solve it

System.out.print("number of terms = ");

System.out.println(allTerms.size());

System.out.print("number of documents = ");

System.out.print("number of documents = ");

System.out.println -> Sends the output to a standard output stream. Generally monitor.

System.err.println -> Sends the output to a standard error stream. Generally monitor.

System.out.print ("He");  
System.out.print ("llo ");  
System.out.println ("World");  

is guaranteed to print "Hello World", but

System.out.print ("He");  
System.err.print ("llo ");  
System.out.println ("World");  

might print "llo He World" or "HeWorld llo". They are 2 different streams.

System.err.print() prints to stderr which may not show up in the console. Switch them to System.out.print()

System.err and System.ou are two different things. With System.out you are writign to stdout with system.err you are writing to stderr.

Try to replace System.err with System.out and you see that your problem disappear.

Then you have to replace:

System.err.print("number of terms = ");

with

System.out.print("number of terms = ");

To change the color of the println check that question: How to color System.out.println output?

After every print* statement, use respective stream's flush method. That may give you desired out put.

System.err.print("number of terms =   "); System.err.flush();  
System.out.println(allTerms.size()); System.out.flush();  
System.err.print("number of documents =   "); System.err.flush();  
System.out.print( numberOfDocuments ); System.out.flush();  

Will result in:

number of terms =   10
number of documents =   1000

Hoping you are doing a console app, and as you expected err prints in red.

这可能是原因: errout都有一个不同的输出流,它将根据访问控制台的顺序打印。

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