2011-11-06 205 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

相关问题