How do I fix the error where I cannot make a static reference to a non-static input field?

后端 未结 5 661
刺人心
刺人心 2021-01-26 22:38

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

相关标签:
5条回答
  • 2021-01-26 22:57

    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.

    0 讨论(0)
  • 2021-01-26 22:57

    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);
    }
    
    0 讨论(0)
  • 2021-01-26 23:03

    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);
    
    0 讨论(0)
  • 2021-01-26 23:04

    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);
    
    0 讨论(0)
  • 2021-01-26 23:20

    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
          }
    
    0 讨论(0)
提交回复
热议问题