簡體   English   中英

想在第二堂課中閱讀用戶輸入和調用方法

[英]Want to read user input and call method in a second class

您好,StackOverflow,

簡短版:如果我有一個名為secondCommand的字符串,並且該字符串是我想在另一個類中調用的方法,那么如何使用格式為“ Circle.secondCommand”的字符串來實際調用該方法?

加長版:我正在編寫一個有關形狀處理的程序-目前我僅使用Circle,但一旦Circle正常工作,我將擴展到使用3種形狀。 目前我的程序如下:

InputReader掃描用戶輸入,分別返回每個單詞輸入。 這在我的ShapeProgrammer類中以“執行”的方法進行處理。 目前的方法是這樣的:

private void execute(String[] commands)
{
    String firstCommand = commands[0];
    String secondCommand = commands[1];
    String thirdCommand = commands[2];
    {
        Circle c = shapes.get(firstCommand);
        if(firstCommand.equals("circle")) {
        makeACircle(commands);
        }
        else if(c != null){
            int newInt = Integer.parseInt(thirdCommand);
            if (newInt != null)
                Circle.secondCommand(newInt);              
            c = null;
        }
        else if(firstCommand.equals("help")) {
        printHelp();
        }
        else {
        System.out.println("Unknown command: " + firstCommand);
        }
    }
}

String []命令在更早的方法的while語句中定義,如下所示:

String[] commands = reader.getInput();

我為每種形狀在單獨的類中提供了形狀本身的所有方法-我已經將Execute寫入了Execute方法中,但是NetBeans卻給了我各種各樣的錯誤。

將要求用戶(並)要求他們以特定格式輸入命令:

創建形狀時,它將是形狀名稱

字符串是名稱時,每個形狀都存儲在HashMap中

當想要編輯/使用形狀時,它將是name命令變量 -我想我已經從HashMap調用形狀了,現在我只是想知道如何使我的字符串secondCommand可用以調用來自另一類的方法。

附帶說明一下,我有int newInt = Integer.parseInt(thirdCommand),因為我的一些方法是用於changeSize或需要int輸入。 我可以擺脫它,並把它放到Circle類中,如果那樣會更容易,那么我只需要在其他方法中調用thirdCommand字符串,然后在那里轉換為int即可。

我認為反射API可能會對您有所幫助。 這是按名稱調用方法的簡單方法。 教程可以為您提供幫助。 基本上:

        String methodName = ***;
    Class classToBeInvoked = **.class;

    Method javaMethod = classToBeInvoked.getMethod(methodName, <arguments-type>);
    Object returnType = javaMethod.invoke(classToBeInvoked, <arguments>);

解決它的另一種方法(不像反射那樣優雅),

為什么不在String數組中定義所有這些方法,並在switch-case塊中使用它們呢?

////////// In your end method ////////
switch (secondCommand) {
    case "DIAGON":
        Circle.diagon();
        break;

    case "THING":
        Circle.thing();
        break;

    case "ANOTHERFORMULA":
        Circle.anotherFormula();
        break;

    default:
        System.out.println("Daamn good.");
        break;
}

如果您不想成為英雄,可以使用這樣的方法名稱,並且會很好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM