2015-10-06 58 views
1

這段代碼工作爲什麼變量在「;」之後未被識別在Java中

public static void main(String[] args) { 
//print from 1-100 

    for (int i = 0; 
     i < 100; 
     i ++) 
    { 
    System.out.print(i + "\n "); 
    } 
} 

但是這一次沒有。

public static void main(String[] args) { 
//print from 1-100 
    for (int i = 0; 
     i < 100; 
     i ++);  // Why does ; stop i from being recognized? 
    { 
    System.out.print(i + "\n "); 
    } 
} 

爲什麼將停止變量;i++)System.out.print(i + "\n ");被認可?

這是Java獨有的嗎?

+0

可能重複的[我不能解析爲一個變量,我正在寫一個Java程序,它將字符串作爲參數反轉](http://stackoverflow.com/a/32665527/3841803) – silentprogrammer

+1

將一個分號後你的循環意味着你以後沒有身體。這意味着'i'不再在範圍中定義。 –

+0

可能重複的[我不能解析爲一個變量。我正在寫一個Java程序,將字符串作爲參數反轉](http://stackoverflow.com/questions/32665469/i-cannot-be-resolved-to-a -variable-i-am-writing-a-java-program-which-reverses-a) – Tom

回答

12

額外;在端部是指在for循環變成這樣:

for(int i = 0; i < 100; i++) { 
    //Empty 
} 

因此,在這種片的代碼:

{ 
System.out.print(i + "\n "); 
} 

i超出範圍並且不能被識別,因爲你的代碼基本上是這樣的:

for (int i = 0; 
    i < 100; 
    i ++)  // Why does ; stop i from being recognized? 
{/*FOR LOOP*/} 
{ 
System.out.print(i + "\n "); //i is out of scope here. 
} 
+1

@Tom:謝謝。固定。 – npinti

0

沒有一個for循環在Java中定義了很多其他語言如:

BasicForStatement: 
for (ForInitializer? ; ForConditionExpression? ; ForPostExpression?) Statement 

這個語句可以是一個塊,就像這樣:

for(...){ 
    ... 
} 

或獨立聲明。一個孤獨的;被解釋爲禁止使用聲明。因此:

for (int i = 0; 
    i < 100; 
    i ++); // <-- statement that executes in the for-loop 
{ // <-- this block doesn't belong to the for-loop 
System.out.print(i + "\n"); 
} 

由於在塊中的代碼然後不屬於環路,i不在範圍。

+0

你說的表達,但你可能意味着聲明 - 他們不是一回事。 – skeggse

+0

@skeggse sry,我有時會把它們混淆 – Paul

+0

不用擔心,我的評論很簡短,但並不是簡單的。 – skeggse

0

你的循環是

for (int i = 0; i < 100; i ++) 
     ; 

相當於您可以避免花括號在for循環(但是是不好的做法),如果你只有一個語句來執行進入循環。

如果添加大括號,你有:

for (int i = 0; i < 100; i ++) { 
    ; 
    System.out.print(i + "\n "); 
} 

正如你可以看到你有一個單一的;這是一個NOP指令的等價物。但是進入循環,所以花括號之間的所有內容都將被執行。

給你一點提示:以更好的方式格式化你的代碼,以清晰的方式查看發生了什麼。