2015-06-28 57 views
0

我想創建一個程序,可以根據用戶輸入從另一個代碼中完成所有內容。類似這樣的:如何在一個類中執行不同的類

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 
     } 
    } 
} 

我該怎麼做?

+0

閱讀哎呀Concept.Constructor,方法調用等 – Madhan

+1

只是叫你所需要的方法:'Main_Program2 .method();'... – assylias

+0

導入這兩個類並調用它們的主要方法,如Main_Programm2.main(args);這應該工作。 –

回答

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(); 
     //..... 
    } 
    } 
} 
相關問題