Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot call method in main method

Tags:

java

I'm trying to call a method in another method (like in C#), like this:

public class Exercise1
{
   Scanner scanner = new Scanner(System.in);
   public int FirstNumber;
   public int SecondNumber;
   public int Answer;

   public static void main(String [] args)
   {
       GetNumbers();
   }

   private void GetNumbers()
   {
       System.out.print("Type in the first number: ");
       FirstNumber = scanner.nextInt();

       System.out.print("Type in the second number: ");
       SecondNumber = scanner.nextInt();

       Answer = FirstNumber + SecondNumber;

       System.out.print("The answer is: " + Answer);
   }
}

Why can't I call the method like that?

like image 423
etritb Avatar asked Mar 09 '26 21:03

etritb


1 Answers

You cannot access non static methods in a static context.

Since main method is static you cannot access non static methods inside it.

Possible solutions:

Solution 1.

Make your GetNumbers(); as static. Then you are able to access it.

  private static void GetNumbers()
   {
      }

But, I won't recommend in your case, because you are accessing other instnace mebers too in GetNumbers() method. So they also needs to be static.

Solution 2.

Create new object for Exercise1 class inside main method.

  public static void main(String [] args)
   {
       Exercise1 ex= new Exercise1();
       ex.GetNumbers();
   }

   private  void GetNumbers()
   {
       System.out.print("Type in the first number: ");
       FirstNumber = scanner.nextInt();

       System.out.print("Type in the second number: ");
       SecondNumber = scanner.nextInt();

       Answer = FirstNumber + SecondNumber;

       System.out.print("The answer is: " + Answer);
   }

And as a side note:

Please follow java naming conventions, variable names stats with small letter's.

   public int firstNumber;
   public int secondNumber;
   public int answer;
like image 156
Suresh Atta Avatar answered Mar 11 '26 11:03

Suresh Atta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!