Get answer from user input and pass to another class

血红的双手。 提交于 2020-01-05 06:27:39

问题


I am trying to accept user input and then pass that input to another class in order to perform a series of checks. In this case, to compare the answer to a list of options that a user can type and if they type an option an action will be performed. I am starting with a menu option but I type 'menu' in the console, nothing happens...the program just terminates without an error.

In debugging, at the 'return;' the value 'menu' is stored in the variable 'answer'. The very next step after that I get "Thread [main] (Suspended)" and this stack trace message:

Thread.exit() line: not available [local variables unavailable]

How do I get the answer to be recognized in my Exec class from the main()?

Here is my main():

package program2;
public class Calculator {
    public static String answer;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the word menu: ");
        String answer = sc.nextLine();
        return;
    }
}

Here is my Exec class where I am trying to perform actions:

package program2;

public class Exec {
    String newAnswer = Calculator.answer;

    public Exec (String answer){        
        if (newAnswer.equals("menu")){
            menu();
        }   
    } 
    public static void menu(){
        System.out.printf("%-30s %-30s %-30s%n", "Enter value: enter", "Duplicate: dup" "Exp:exp");        
    }
}  

I also tried something simpler like this (received the same response):

package program2;
public class Calculator {
    public static String answer;

    public static void main(String[] args) {
        answer = "menu";
        return;
    }
}

回答1:


For starters, you need to instantiate an instance of Exec from main, and pass it into Exec... i.e.:

String answer = sc.nextLine();
Exec ex = new Exec(answer);
return;

From there, it should work. It said that there were no more variables available, because your program ends at that return statement...

But you also have problems in your Exec class.... newAnswer isn't assigned and you are testing it for equality... you will get another error...

Edit:

ugg.. its even worse than that... do not redeclare answer, use this.answer... you are declaring a new local variable.



来源:https://stackoverflow.com/questions/15581898/get-answer-from-user-input-and-pass-to-another-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!