Get answer from user input and pass to another cla

2019-07-29 14:43发布

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条回答
老娘就宠你
2楼-- · 2019-07-29 15:11

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.

查看更多
登录 后发表回答