简体   繁体   English

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

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

I want to print "hello" without using semicolon.While using for loop for printing hello i came to know println and printf both can be used for printing hello.我想在不使用分号的情况下打印“hello”。在使用 for 循环打印 hello 我开始知道 println 和 printf 都可以用于打印 hello 。 But in case of if only printf is used for printing hello.When i used println in if statement its showing "void type not allowed here".What does this error means and why println cannot be used in if statement??但是如果只有 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)
{}
}
}

The reason is printf returns PrintWriter which you can compare to null .原因是printf返回PrintWriter ,您可以将其与null进行比较。 println returns void ie nothing which you can't compare to null. println返回void即您无法与null进行比较的任何内容。 A couple of additional options to print without using semicolon in your program are while and try .在程序中不使用分号进行打印的几个附加选项是whiletry All the mentioned options:所有提到的选项:

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

One additional option and my favorite is to tell the interviewer that you refuse to answer stupid questions but that's a luxury not everybody have.另一个选择,我最喜欢的是告诉面试官你拒绝回答愚蠢的问题,但这不是每个人都有的奢侈。

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

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