Java 用 printf 打印一个布尔值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27209450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 03:59:01  来源:igfitidea点击:

Print a boolean value with printf

javabooleanprintf

提问by darbulix

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

我想用 打印一个booleanprintf,但我不知道如何。我正在寻找的是类似这个虚构代码的东西

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?

我该怎么做?或者有没有其他方法可以获得预期的输出?

回答by sinister

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

好消息是它打印了 value true,你想象中的代码没有任何问题。或者你也可以尝试

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

回答by Elliott Frisch

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()

我假设您遇到了缓冲问题,以至于您的程序在缓冲区刷新之前退出。当您使用printf()orprint()它不一定在没有换行符的情况下刷新。您可以使用显式flush()

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

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

或添加一个新行(这也会导致flush()

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

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

另请参阅Buffered Streams - The Java Tutorials, Flushing Buffered Streams部分说明

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 PrintWriterobject flushes the buffer on every invocation of printlnor format.

一些缓冲输出类支持autoflush,由可选的构造函数参数指定。启用自动刷新后,某些关键事件会导致缓冲区被刷新。例如,自动刷新PrintWriter对象在每次调用printlnor 时刷新缓冲区format

回答by Vlad

boolean car =true;

System.out.println(""+car);