2017-12-18 309 views
-2

我試圖在兩者之間的if-and-else語句中創建一些Java代碼。當我運行代碼時,預期輸出應該是:「hello world hello world」,但我得到的是「hello hello hello hello」在if和else語句中更改整數值

我不知道我在這裏做錯了什麼。有人可以告訴我這個問題嗎?

int p = 1; 

for (int i = 1; i < 5; i++) { 
    if (p == 1) {  
     System.out.println("hello"); 
     p = 2; 
    } else { 
     System.out.println("world"); 
     p = 1; 
    } 
} 
+0

你確定這是打印? –

+1

檢查你的花括號 – ajb

+0

順便說一下,標準的縮進實踐是'for'塊中的所有內容都應該縮進到'for'的右側。在這裏,你有第一個'if'開始於'for'的同一列,而不是縮進它。如果你縮小了它,你可能會自己發現問題。 – ajb

回答

0

根據@ajb評論,你只需動p = 1else塊:

for (int i = 1; i < 5; i++) { 
    if (p == 1) { 
     System.out.print("hello"); 
     p = 2; 
    } else { 
     System.out.print("world\n"); 
     p = 1; 
    } 
} 
2

這是不是所有你的代碼在你的程序,但看看這裏:

else 
     System.out.println("world"); 
    p = 1; 
} 

最後的大括號不屬於if-else聲明的else部分,它屬於for循環,其中包含if-else部分 - 改進代碼的格式,您將看到不同之處。您的else零件沒有用花括號包圍,因此只有在執行第二個條件時執行else字後的第一行。

0

您在else塊上缺少大括號。

int p = 1; 

for(int i = 1; i < 5; i++){ 
    if (p == 1){  
     System.out.println("hello"); 
     p = 2; 
    } 
    else { 
     System.out.println("world"); 
     p = 1; 
    } 
}