一、if-else聲明

如果不管外部環境如何變化,程序總是做同樣的事情,那麼它們就不會很有用。一個程序需要能夠適應不同的情況並在某些情況下採取某些行動,而在其他情況下採取不同的行動。

在 Java 中,這是通過條件語句完成的,它使用特殊關鍵字讓您根據條件的真值執行不同的命令塊。

條件語句由三部分組成:條件語句 1語句 2。如果條件為真,則執行語句 1 。否則執行語句 2 。這兩個命令都不會執行。下面是這種語句的一般外觀:

if (condition)
   statement 1;
else
   statement 2;
條件if-else語句

像這樣用簡單的英語寫是很容易理解的:

If condition is true, then
   execute statement 1;
otherwise
   execute statement 2;
if-else通俗易懂的聲明

例子:

代碼 解釋
int age = 17;
if (age < 18)
   System.out.println("You are still a child");
else
   System.out.println("You are now an adult");
屏幕輸出將是:
You are still a child
int temperature = 5;
if (temperature < 0)
   System.out.println("It's freezing outside");
else
   System.out.println("It's warm");
屏幕輸出將是:
It's warm
int age = 18;
if (age == 18)
   System.out.println("You've been drafted for military service");
else
   System.out.println("Report for duty anyway");
屏幕輸出將是:
You've been drafted for military service


2.語句塊

如果滿足(或不滿足)條件並且您希望您的程序執行多個命令,則可以將它們組合成一個

要將命令組合成一個塊,您可以將它們“包裹”在花括號中。這是它的一般外觀:

{
   statement 1;
   statement 2;
   statement 3;
}

您可以在一個塊中包含任意多的語句。甚至沒有。

if-else語句與語句塊組合的示例:

代碼 解釋
int age = 17;
if (age < 18)
{
   System.out.println("You are still a child");
   System.out.println("Don't talk back to adults");
}
else
{
   System.out.println("You are now an adult");
   System.out.println("And thus ends your youth");
}
屏幕輸出將是:
You are still a child
Don't talk back to adults
int temperature = 5;
if (temperature < 0)
{
   System.out.println("It's freezing outside");
   System.out.println("Put on a hat");
}
else
   System.out.println("It's warm");
屏幕輸出將是:
It's warm
int age = 21;
if (age == 18)
   System.out.println("You've been drafted for military service");
else
{
}
空塊將被執行。
代碼可以正常運行,但不會顯示 任何內容。

if3.聲明的縮寫形式

有時,如果條件為真,您需要執行一個或語句 ,但如果條件為假,則什麼都不要做。

例如,我們可以指定此命令:,但如果總線不在此處則不要做出反應。在 Java 中,這種情況讓我們使用縮寫形式:沒有塊的語句。If Bus No. 62 has arrived, then get aboardifelse

換句話說,如果只有條件為真時才需要執行語句,條件為假時沒有要執行的命令,那麼你應該使用語句if,它簡潔並且省略了else塊。它看起來像這樣:

if (condition)
   statement 1;
條件if語句

以下是等效代碼的三個示例:

代碼 解釋
int age = 18;
if (age == 18)
{
   System.out.println("You've been drafted for military service");
}
else
{
}
屏幕輸出將是:
You've been drafted for military service

該程序有一個else塊,但它是空的(花括號之間沒有語句)。你可以簡單地刪除它。程序中沒有任何變化。

代碼 解釋
int age = 18;
if (age == 18)
{
   System.out.println("You've been drafted for military service");
}
屏幕輸出將是:
You've been drafted for military service
int age = 18;
if (age == 18)
   System.out.println("You've been drafted for military service");
屏幕輸出將是:
You've been drafted for military service