从用户输入获取答案并传递给另一个类 [英] Get answer from user input and pass to another class

查看:264
本文介绍了从用户输入获取答案并传递给另一个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试接受用户输入,然后将该输入传递给另一个类,以便执行一系列检查。在这种情况下,要将答案与用户可以键入的选项列表进行比较,如果他们键入选项,将执行操作。我从菜单选项开始,但我在控制台中键入菜单,没有什么发生...程序只是终止,没有错误。

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.

在调试中,在'return;',值'menu'存储在变量'answer'中。接下来的步骤,我得到Thread [main](Suspended)和这个堆栈跟踪消息:

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行:不可用[局部变量不可用]

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

如何让我的Exec类中的答案从main ?

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

这是我的 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;
    }
}

这是我要执行的Exec类动作:

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


推荐答案

启动器,你需要从main实例化一个Exec的实例,并将其传递给Exec ...
ie:

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;

从那里,它应该工作。它说没有更多的变量可用,因为你的程序结束于那个return语句...

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

但是你的Exec类也有问题... newAnswer未分配,您正在测试它是否相等...您会得到另一个错误...

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

编辑:

ugg ..它甚至比这更糟糕...不要重新声明答案,使用 this.answer ...你正在声明一个新的局部变量。

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

这篇关于从用户输入获取答案并传递给另一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆