gpt4 book ai didi

java - 如何修复 Main 中调用的非静态方法?

转载 作者:行者123 更新时间:2023-12-02 09:05:11 25 4
gpt4 key购买 nike

我想在 Main 中调用一个非静态方法,但这违反了编码规则,所以现在我不能做我想做的事情。我该如何解决这个问题?

public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter infix expression: ");
String userInput = input.next();
System.out.println("Summary");
System.out.println("-------");
System.out.println("Infix: " + userInput);
System.out.println("Postfix: " + infixToPostfix(userInput));
System.out.println("Result: " + evalPostfix(infixToPostfix(userInput)));
}

我收到错误:

non static method infixToPostfix(java.lang.string) cannot be refranced from a static context

non static method evalPostfix(java.lang.string) cannot be refranced from a static context

我需要在这里使用它们来打印正确的答案。

最佳答案

快速修复:

将您的 infixToPostfix(...)evalPostfix(...) 方法设为静态。

更多面向对象的修复:

您的静态 main 方法应该实例化包含 infixToPostfix(...)evalPostfix(...) 的类的实例,该类可能是包含 main 的类方法:

public static void main(String[] args)
{
MyClass myClass = new MyClass(); // make an instance

Scanner input = new Scanner(System.in);
System.out.print("Enter infix expression: ");
String userInput = input.next();
System.out.println("Summary");
System.out.println("-------");
System.out.println("Infix: " + userInput);
System.out.println("Postfix: " + myClass.infixToPostfix(userInput)); // use your instance
System.out.println("Result: " + myClass.evalPostfix(infixToPostfix(userInput))); // use your instance
}

关于java - 如何修复 Main 中调用的非静态方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59870551/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com