簡體   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