如何在一个类中执行不同的类

时间:2015-06-28 09:18:18

标签: java class

我想创建一个程序,可以根据用户输入从其他代码执行所有操作。像这样:

import java.util.Scanner;
public class Main_Programm1 {
    public static void main(String args[]) {
        String something = "something";
        String something2 = "something2";
        Scanner userInput = new Scanner(System.in);
        String action = userInput.next();
        if (action.equals(something)) {
            //here i want to execute all the code from class Main_Programm2
        } else if (action.equals(something2)) {
            //here i want to execute all the code from class Main_Programm3 and so on
        }
    }
}

我该怎么做?

1 个答案:

答案 0 :(得分:1)

实际上,你已经完成了所有工作,只创建了你需要的对象; - )

import java.util.Scanner;
// imports classes;

public class Main_Programm1 
{
  public static void main(String args[]) 
  {
    String something = "something";
    String something2 = "something2";
    Main_Programm main_prog;
    Main_Programm2 main_prog2;

    Scanner userInput = new Scanner(System.in);
    String action = userInput.next();
    if (action.equals(something)) 
    {
      main_prog = new Main_Programm();
      //.....
    } 
    else if (action.equals(something2)) 
    {
      main_prog2 = new Main_Programm2();
      //.....
    }
  }
}