I am learning java. I wrote the following code but I am getting this error \"cant make a static reference to a non static input field\" in Arrayfunction(), when I try to take in
A non static
reference is tied to the instances
of the class
. While all static
code is tied to the class
itself.
You must add the static keyword
.
input
in your class is an instance variable (since it's not defined as static
), which means that each instance of MultidimArrays
has one of it's own. static
fields or methods (often referred to as "class variables/methods" are shared between all instances of a class.
Since Arrayfunction
is static
, it cannot refer to instance members of its class - there is no way for it to know which MultidimArray
to use. You can either solve this by making input
itself static, or by removing the static
qualifier from ArrayFunction
and create an instance of your class:
public static void main(String args[])
{
int array[][] arr = new int[2][3]; //typo here, variable needs a name :)
System.out.println("Passing array to a function");
MultidimArray ma = new MultidimArray();
ma.Arrayfunction(arr);
}
The reason for this error is: As you have not created the object the non-static variable input
does not exist, so you can not use it.
To fix it you can make input
as static
static Scanner input= new Scanner(System.in);
Scanner is not defined as static therefore is in the wrong scope
Either create the Scanner instance inside Arrayfunction
or create your scanner with
private static Scanner input= new Scanner(System.in);
either make your Scanner static and use it inside the static methods or create an instance of the class an access scanner from your static method.
static Scanner input= new Scanner(System.in);
public static void Arrayfunction(int array[][])
{
System.out.println("Enter a number");
array[i][j]=input.nextInt();// error
}
OR
Scanner input= new Scanner(System.in);
public static void Arrayfunction(int array[][])
{
System.out.println("Enter a number");
array[i][j]=new MultidimArrays().input.nextInt();// error
}