3

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?

user unknown
  • 35,537
  • 11
  • 75
  • 121
William Kinaan
  • 28,059
  • 20
  • 85
  • 118

7 Answers7

9

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.

Christopher Oezbek
  • 23,994
  • 6
  • 61
  • 85
3

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.

Habib
  • 219,104
  • 29
  • 407
  • 436
3
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.

Snake
  • 785
  • 1
  • 5
  • 13
2

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

2

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?

Community
  • 1
  • 1
Ivan
  • 4,186
  • 5
  • 39
  • 72
1

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.

Ravinder Reddy
  • 23,692
  • 6
  • 52
  • 82
0

This might be the reason: err and out both have a different ouptput stream which will print according to the sequence of getting access to the console.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
RTA
  • 1,251
  • 2
  • 14
  • 33