Java';System.err.format';使用';%n';其次是';System.out.println',版画在中间
我对Java非常陌生 我使用的是Ubuntu 16.04、JDK 8u101、Netbeans8.1 尝试此代码时:Java';System.err.format';使用';%n';其次是';System.out.println',版画在中间,java,ubuntu,Java,Ubuntu,我对Java非常陌生 我使用的是Ubuntu 16.04、JDK 8u101、Netbeans8.1 尝试此代码时: public static void main(String[] args) { System.err.format("1st Line %nPrints At 3rd Line,Shouldn't this be In 2nd Line "); System.out.println("Shouldn't this be the third line,prints
public static void main(String[] args) {
System.err.format("1st Line %nPrints At 3rd Line,Shouldn't this be In 2nd Line ");
System.out.println("Shouldn't this be the third line,prints at 2nd line");
}
输出为:
This Prints At 1st Line
Shouldn't this be the third line, but prints at 2nd line
This Prints At 3rd Line, Shouldn't this be In 2nd Line
为什么“<代码>系统?out .PrtLNN<代码>”在中间打印?
它不应该持续打印吗
我在末尾尝试了“%n
”&System.err.flush()
,如下所示:
System.err.format("1st Line %nPrints At 3rd Line,Shouldn't this be In 2nd Line%n");
System.err.flush();
System.out.println("Shouldn't this be the third line,prints at 2nd line");
仍然是相同的输出。您没有在println()
调用和System.out
和System.err
之间调用,它们都(独立地)缓冲PrintStream
//最后需要一个%n才能生成3行。
System.err.format(“第1行%n在第3行,这不应该在第2行%n中”);
System.err.flush();//您正在打印到两个不同的流,这两个流仅在一行的末尾刷新,但System.err在其第二行的末尾没有刷新。System.err
没有刷新,因为它的末尾没有换行符。因此,您需要手动冲洗+1如果您添加%n,我认为您不需要刷新()@PeterLawrey Correct。Javadoc可选地说,可以创建打印流
,以便自动刷新;这意味着在写入字节数组、调用某个println
方法或写入换行符或字节('\n'
)后,会自动调用flush
方法。我尝试了该代码。我复制粘贴、保存,然后再次运行粘贴。我得到了相同的输出。@Jit也重新编译。我使用的“清理并构建项目”仍然是相同的输出。我做错什么了吗@Elliott Frisch
// and you need a %n on the end to make 3 lines.
System.err.format("1st Line %nPrints At 3rd Line,Shouldn't this be In 2nd Line%n");
System.err.flush(); // <-- only needed if the previous write doesn't have
// an implicit flush(); newline (%n) does.
System.out.println("Shouldn't this be the third line,prints at 2nd line");