0

I want to call a non static method in Main, but thats against coding rules, so now i cant do the things i want. How can i fix this?

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

I'm getting the error:

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

and

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

I need to use them here to get the correct answers printed.

1 Answers1

0

Quick fix:

Make your infixToPostfix(...) and evalPostfix(...) methods static.

More object-oriented fix:

Your static main method should instantiate an instance of the class containing infixToPostfix(...) and evalPostfix(...) which could be the class containing the main method:

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
}
Jason
  • 11,744
  • 3
  • 42
  • 46
  • The static fix worked for my program. Although the class fix looked cool, but will not work because my program isnt object orented. Thank you! –  Jan 23 '20 at 01:57
  • You are coding in Java, therefore your program is object oriented. Even if you only have one object - the one containing your main method. – Jason Jan 23 '20 at 01:58
  • Yeah, i giess you are right. I just meant, i am only working with one class, everything else is done in methods. –  Jan 23 '20 at 01:59
  • Well that is still not a convincing reason. The object could be an instance of the class that defines the `main` method. If you are writing in Java, you should be writing OO (and avoiding static) unless there is a compelling reason not to. Even for small things. It is only about 1 line of extra code to create a trivial instance of the current class so that you can invoke methods on it. – Stephen C Jan 23 '20 at 02:03