我在项目中创建了不同的 .java 文件。现在我想创建一个控制台菜单,其中包含单独运行这些类的选项。
public class ConsoleMenuDemo {
public static void main(String[] args) {
// Local variable
int swValue;
// Display menu graphics
System.out.println("============================");
System.out.println("| MENU SELECTION DEMO |");
System.out.println("============================");
System.out.println("| Options: |");
System.out.println("| 1. Option 1 |");
System.out.println("| 2. Option 2 |");
System.out.println("| 3. Exit |");
System.out.println("============================");
swValue = Keyin.inInt(" Select option: ");
// Switch construct
switch (swValue) {
case 1:
System.out.println("Option 1 selected"); // This is where I want to call the class
break;
case 2:
System.out.println("Option 2 selected"); // this is where I want to call the class
break;
case 3:
System.out.println("Exit selected");
break;
default:
System.out.println("Invalid selection");
break; // This break is not really necessary
}
}
}
最佳答案
您不是“调用类”,而是调用类的构造函数或静态方法。据推测,您还有其他具有自己的构造函数和实例方法的公共(public)类。如果是这种情况,只需确保所有类都在同一个包中,然后您就可以简单地编写:
case 1:
System.out.println("Option 1 selected"); // This is where I want to call the class
Class1 class1 = new Class1();
class1.doSomething();
break;
case 2:
System.out.println("Option 2 selected"); // this is where I want to call the class
Class2 class2 = new Class2();
class2.doSomethingElse();
break;
关于java - 如何制作java控制台菜单并使用这些选项调用项目中的不同java文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21983811/