繁体   English   中英

为什么在 if 语句中打印 hello 时使用“printf”而不是“println”

[英]Why to use "printf" instead of "println" while printing hello in if statement

我想在不使用分号的情况下打印“hello”。在使用 for 循环打印 hello 我开始知道 println 和 printf 都可以用于打印 hello 。 但是如果只有 printf 用于打印 hello。当我在 if 语句中使用 println 时,它显示“此处不允许使用 void 类型”。这个错误是什么意思,为什么 println 不能在 if 语句中使用?

public class withoutsemicolon
{ 
public static void main(String [] args)
{   
for(int i=0;i<=4;System.out.println("hello"+i+"\n"),i++)
{}
if(System.out.println("hello"+"\n")!=null)
{}
}
}

原因是printf返回PrintWriter ,您可以将其与null进行比较。 println返回void即您无法与null进行比较的任何内容。 在程序中不使用分号进行打印的几个附加选项是whiletry 所有提到的选项:

if(System.out.printf("hello\n") == null){}
while(System.out.printf("hello\n") == null){}
try(Closeable c = System.out.printf("hello\n")){}

另一个选择,我最喜欢的是告诉面试官你拒绝回答愚蠢的问题,但这不是每个人都有的奢侈。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM