2014-06-12 78 views
-4

爲什麼輸出「休息」和「學習?」它不應該只是「學習」嗎?兩條if語句的輸出

boolean isSleeping = false; 
    boolean isStudying = true; 
    if (isSleeping) 
     System.out.println(" Sleeping "); 
     System.out.println(" Resting "); 
    if (isStudying) 
     System.out.println(" Studying "); 
+4

因爲'System.out.println(「Resting」);'不在第一個if語句中。 – immibis

+2

大括號定義塊的範圍.. – TheLostMind

+1

Python轉換? – usr2564301

回答

1
if (isSleeping) 
    System.out.println(" Sleeping "); // your if condition's scope ends here 
    System.out.println(" Resting ");// always printed 
if (isStudying) 
    System.out.println(" Studying "); // your second if condition's scope ends here 
1

使用{ }如果要執行兩個語句。

像這樣:

if (isSleeping) { 
    System.out.println(" Sleeping "); 
    System.out.println(" Resting "); 
} 
else if (isStudying) { 
    System.out.println(" Studying "); 
} 

我已經編輯和添加else也因爲symentically有人睡覺或休息不學習。

1

if語句後面添加大括號,如果您想要爲該條件執行更多語句。

boolean isSleeping = false; 
    boolean isStudying = true; 
    if (isSleeping){ 
     System.out.println(" Sleeping "); 
     System.out.println(" Resting "); 
    } 
    if (isStudying) 
     System.out.println(" Studying "); 
3

基本上,因爲你已經不是封閉的第一if語句內容{...}之間,它基本上是qualivent的話說...

if (isSleeping) 
    System.out.println(" Sleeping "); 

System.out.println(" Resting "); 

if (isStudying) 
    System.out.println(" Studying "); 

相反,使用嘗試...

if (isSleeping) { 
    System.out.println(" Sleeping "); 
    System.out.println(" Resting "); 
} 
if (isStudying) { 
    System.out.println(" Studying "); 
} 

這就是爲什麼鼓勵在您的條件語句周圍使用大括號的原因之一

1

您的if語句不使用{...}。因此,它會考慮您的if以外的第二行。

試試這個:

boolean isSleeping = false; 
boolean isStudying = true; 
if (isSleeping) {       // the following code between brackets will be executed. 
    System.out.println(" Sleeping "); 
    System.out.println(" Resting "); 
} 
if (isStudying) 
    System.out.println(" Studying ");  // Without bracket, it executes only the line until the semi-colon. 
1

讀什麼範圍:SCOPE

if聲明沒有{}具有爲範圍的代碼條件後的第一行..

不過,如果你想要打印只能睡你必須做的:

boolean isSleeping = false; 
    boolean isStudying = true; 

    if (isSleeping){ 
     System.out.println(" Sleeping "); 
    } 

     System.out.println(" Resting "); 

    if (isStudying){ 
     System.out.println(" Studying "); 
    } 
1
if(true) 
line 1 
line 2 

上述if語句是不帶括號{} ..這意味着if語句僅適用於剛剛後IF語句的線(線1)..

if(true) 
{ 
line 1 
line 2 
} 

if語句上面括號是人的brackets..this的全身= pplicable同時適用於線1和線2 ..

所以你的情況

if (isSleeping) 
    System.out.println(" Sleeping "); 
    System.out.println(" Resting "); 

這個if語句只適用於第一行的「Sleepinfg」於是「休息」是免費的任何IF statement..so「休息」永遠是在輸出文件

你的代碼應該是喜歡這個..

boolean isSleeping = false; 
boolean isStudying = true; 
if (isSleeping) 
{ 
    System.out.println(" Sleeping "); 
    System.out.println(" Resting "); 
} 
if (isStudying) 
{ 
    System.out.println(" Studying "); 
}