Java 定义的类给出了未定义的类错误

Java 定义的类给出了未定义的类错误,java,Java,对于方法showTotal问题,我得到了一个未定义的方法,即使该方法已定义 public class Test { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String command ; Machine M = null; while(true) { System.out.println("Enter your command");

对于方法showTotal问题,我得到了一个未定义的方法,即使该方法已定义

public class Test {
public static void main(String[] args) {
 Scanner sc = new Scanner(System.in);
 String command ;
 Machine M = null;
    while(true)
    {
        System.out.println("Enter your command");
        command = sc.next();
        String[] commands = command.split(" ");
        if (commands[0] == "create" )
        {
           M = new Machine (commands[1],commands[2]);
        }

        else if (commands[0] == "total" )
        {
            M.showTotal();
        }



    }
}
}

您需要为扫描仪调用nextLine而不是next

    command = sc.next();
    String[] commands = command.split(" ");
您将无法拆分string命令,因为您正在使用next命令,因此该命令中永远不会有空格。改变它,这样你就可以像这样抓住整条线

    command = sc.nextLine(); //grab the line
    String[] commands = command.split(" ");
然后,如果您的语句需要对字符串使用equals方法,==将不会以您希望的方式比较java中的字符串。您还需要确保split返回的数组长度>=3,以防止索引超出范围,并在调用showTotal时检查M是否为null

    if (commands[0].equals("create") && comands.length() >= 3)
    {
       M = new Machine (commands[1],commands[2]);
    }

    else if (commands[0].equals("total") && M != null)
    {
        M.showTotal();
    }

脱离主题,但您将命令解析为sc.next,While将只有一个完整的令牌,然后对其调用split。还有,你有一个无限循环。你能展示一下机器类的代码吗?我不确定我是否明白你的意思,你能解释一下吗?当你在创建之前调用total时会发生什么?另外,机器类代码也会有帮助。我不知道如何把它复制到这里。引擎一直告诉我它有太多的代码,所以它就在这里