我想制作一个有 3 个选择的简单菜单:
在员工管理器中“创建新员工”、“显示所有员工”和“退出”(代码如下)但没有成功(编译错误)。
BlueJ 编辑器无法实现“case 2”语句中的对象“m”、“s”和“l”。是否有办法获取“情况 1”中对象的值并在“情况 2”中使用它们?非常感谢!
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
int ch;
do{
System.out.println("EMPLOYEE MANAGER\n");
System.out.println("1. Create new employees\n");
System.out.println("2. Display all employees\n");
System.out.println("3. Quit\n");
System.out.print("Your choice: ");
Scanner input = new Scanner(System.in);
ch = input.nextInt();
switch(ch){
case 1: System.out.println("== CREATE NEW EMPLOYEES ==");
System.out.println();
Manager m = new Manager();
Scientist s = new Scientist();
Labourer l = new Labourer();
m.newManager();
s.newScientist();
l.newLabourer();
System.out.println();
break;
case 2: System.out.println("== PREVIEW EMPLOYEES ==");
System.out.println();
m.display();
s.display();
l.display();
System.out.println();
System.out.println();
break;
case 3: System.exit(0);
default: System.out.println("Invalid choice!");
}
} while(ch >= 1 && ch <=4);
}
}
最佳答案
它们是本地 block ,将它们声明在 switch block 之外
Manager m = new Manager();
Scientist s = new Scientist();
Labourer l = new Labourer();
switch(){...}
这很好地回答了您的问题,但我想添加更多细节
如果你不把括号放在 case block 中,例如
switch(i){
case 1:
String str="abc";
System.out.println(str);
case 2:
// it will give you compile time error
//duplcate local variable str
String str="abc";
}
那么这个str
实例在其他case block 中也是可见的
关于java - 如何在 switch-case 语句中获取和设置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11008478/