我正在制作一个包含菜单的程序,我正在使用开关在菜单之间导航。
我有这样的事情:
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中定义的一些值。
如果无法做到这一点,请指出正确的方向。
请记住,我已经开始学习java几周了。
favolas
答案 0 :(得分:3)
在切换之前声明变量,您将能够在所有情况下使用它们
int var1;
switch(number) {
case 1:
var1 = 2;
break;
case 2:
var2 += 3;
break;
...
答案 1 :(得分:1)
每当有大括号时,你就会拥有所谓的不同范围。
如果你在那里创建变量,当你离开那个范围时它们就会丢失。
如果您创建变量BEFORE,则可以使用它。
int subMenu = 0;
switch(...){
...
subMenu = 1;
}
if (subMenu == 1 ){
....
}
即使离开开关也能正常工作。
答案 2 :(得分:0)
如果您尝试在案例1中声明(即:int a = 2)变量,然后在案例2中也使用它,您将收到错误消息:“变量已定义...”。这就解释了为什么你不能这样做,编译器必须知道你在使用它之前声明了一个变量。
如果在switch语句之前声明所有变量,那么你就可以了。一个例子:
int var;
swith(...){
case 1:
var ++;
break;
case 2:
var +=10;
break;
}