Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print a boolean value with printf [closed]

I want to print a boolean value with the printf ,but I do not know how. What I am looking for is something like this imaginary code

boolean car = true;
System.out.printf("%b",car);

The expected output should be:

true

How should I do it? Or are there any other ways to get that expected output?

like image 200
darbulix Avatar asked Nov 30 '14 02:11

darbulix


Video Answer


2 Answers

I assume you are running into a buffering issue, such that your program exits before your buffer flushes. When you use printf() or print() it doesn't necessarily flush without a newline. You can use an explicit flush()

boolean car = true;
System.out.printf("%b",car);
System.out.flush();

or add a new-line (which will also cause a flush())

boolean car = true;
System.out.printf("%b%n",car);

See also Buffered Streams - The Java Tutorials, Flushing Buffered Streams which says in part

Some buffered output classes support autoflush, specified by an optional constructor argument. When autoflush is enabled, certain key events cause the buffer to be flushed. For example, an autoflush PrintWriter object flushes the buffer on every invocation of println or format.

like image 69
Elliott Frisch Avatar answered Oct 23 '22 00:10

Elliott Frisch


The good thing is that it prints the value true, there is nothing wrong with your imaginary code. Alternatively you can also try

boolean car = true;
System.out.print(car);
System.out.printf("%b", car);
like image 30
Piyush Deshmukh Avatar answered Oct 23 '22 00:10

Piyush Deshmukh