2011-11-06 204 views
0

我正在製作一個帶有菜單的程序,並且我正在使用開關在菜單之間導航。Java開關(使用在另一種情況下計算的情況下的值)

我有這樣的事情:

switch (pick) { 
    case 1: 
    // Here the program ask the user to input some data related with students (lets say 
    // name and dob). Student is a class and the students data is stored in 1 array of 
    // students. If I do: 
    // for (Student item: students){ 
    //   if (item != null){ 
    //    System.out.println(item); 
    //   }  
    // } 
    // It will print the name and dob of all the students inserted because I've created 
    // a toString() method that returns the name and dob of the students 

    case 2: 
    // On case 2 at some point I will need to print the array created on the case 
    // above. If I do again: 
    // for (Student item: students){ 
    //   if (item != null){ 
    //    System.out.println(item); 
    //   }  
    // } 
    // It says that students variable might have not been initialized. 

問:

如果一個變量在一個情況下創建它的價值不能在另一種情況下使用? 我試圖做的是首先進入情況1並輸入值,然後,在情況2中能夠使用在情況1中定義的一些值。

如果這不能完成,請點我在正確的方向。

請記住,我已經開始只學幾個禮拜了。

favolas

+0

你說「問題一:」,那裏還有一個「問題二」嗎? –

+0

@java熔岩我的不好。對不起 – Favolas

回答

3

開關之前聲明變量,你就可以在所有情況下使用它們

int var1; 

switch(number) { 
    case 1: 
    var1 = 2; 
    break; 
    case 2: 
    var2 += 3; 
    break; 
    ... 
+1

P.S.不要忘記在每個案例的末尾添加break語句,因爲case標籤中的語句按順序執行直到遇到break。請參閱http://download.oracle.com/javase/tutorial/java/nutsandbolts/switch.html –

+0

謝謝。忘記這一點,並已知道必須休息。 – Favolas

1

每當有大括號,你有什麼被稱爲一個不同的範圍。

如果您在那裏創建變量,則在您離開該範圍時會丟失它們。

如果您創建變量BEFORE,則可以使用它。

int subMenu = 0; 

switch(...){ 

... 
subMenu = 1; 

} 

if (subMenu == 1){ 
.... 
} 

即使離開開關也可以工作。

+0

謝謝。忘記了那個 – Favolas

0

如果你試圖聲明(即中:int a = 2)的情況下,1變量,然後使用它也在情況2你會得到錯誤消息:「變量已經定義...」。這就解釋了爲什麼你不能這樣做,編譯器必須知道你在使用它之前已經聲明瞭一個變量。

如果你在switch-statement之前聲明所有的變量,你會沒事的。舉個例子:

int var; 
swith(...){ 
    case 1: 
    var ++; 
    break; 
    case 2: 
    var +=10; 
    break; 
} 
+0

謝謝。忘了那個 – Favolas

相關問題