-2

import java.util.Scanner;

public class Account { int number1,number2,sum;

public static void main(String[] args) {
    Scanner input = new Scanner (System.in);
    System.out.println("Enter your first number");
     number1 = input.nextInt();
     System.out.println("Enter your Second number");
     number2 = input.nextInt();
     sum = number1 + number2;
     System.out.println("Your Answer is" + sum);
     input.close();
}

}

2 Answers2

0

number1 and number2 and sum are instance variables.

They will not exist until an actual instance of the class is created, and can only be used through said instance of the class.

Since each instance will have it's proper values for them, at this point, the compiler doesn't know anything about them.

You'll want to either declare them locally in your main method, or as static variables in your class:

static int number1;
static int number2;
static int sum;
Stultuske
  • 9,296
  • 1
  • 25
  • 37
0

You cannot refer to non-static variables in static methods without creating objects. The variables number1, number2 and sum in your code are non-static and you are directly referring to them in main() which is declared as static.

If your program does not require multiple objects or if the value of number1, number2 and sum are going to be same for all the objects, you could simply solve the problem by making those variables static.

static int number1, number2, sum;

What does static mean?

  • static variables are class variables which means there is only one copy of that variable for all the objects of the class.

If you would like to have multiple objects of the class Account and different copies of the variable for each object, then you could do the following.

  • Step1 : Keep the variables as it is. Do not make them static.

  • Step2 : Create an object in main() while referring to the non-static variables.

    Inside main():

      Account obj=new Account();
      Account obj1=new Account();
      //objects created and each object has a separate copy of the variables
      obj.number1=....;
      obj.number2=………;
      obj1.number1=……;
      //so on.
    

Summing up:

  • You need to create objects while referring to non-static fields in static methods. Because static methods are class methods and does not belong to a particular object of the class. You could also make the variables static if it isn't a problem.
Mathews Mathai
  • 1,707
  • 13
  • 31