![](/img/trans.png)
[英]Why the content is not printing inside the system.out.println statement while using a boolean statement
[英]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進行比較的任何內容。 在程序中不使用分號進行打印的幾個附加選項是while
和try
。 所有提到的選項:
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.