Getting error while using .nextInt()

痞子三分冷 提交于 2019-12-12 02:42:44

问题


I am getting this error: "cannot make a static reference to the nonstatic field" everytime I try to execute a line of code with .nextInt() in it.

Here are the lines of code that could affect (that I can think of):

private Scanner input = new Scanner(System.in);
int priceLocation = input.nextInt();

回答1:


This is most likely because you're trying to access input in a static method, which I'm assuming it to be the main() method. Something like this

private Scanner input = new Scanner(System.in);

public static void main(String[] args) {
    int priceLocation = input.nextInt(); // This is not allowed as input is not static

You need to either make your input as static or may be move it inside the static(main) method.

Solution1: Make the input as static.

private static Scanner input = new Scanner(System.in);

public static void main(String[] args) {
    int priceLocation = input.nextInt();

Solution2: Move the input inside the main(note that you can't use input in any other methods, if its moved inside the main(), as it'll be local to it).

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int priceLocation = input.nextInt();



回答2:


private Scanner input = new Scanner(System.in); // make this static 

If you accessing this inside static method. you have to make input static.

private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
    int priceLocation = input.nextInt();
   // without static you will get that error.
}



回答3:


This is because of the way you are defining input

private Scanner input = new Scanner(System.in); // notice private
int priceLocation = input.nextInt();

Private variables are defined in the class, outside methods like

class myclass{

    private Scanner input = new Scanner(System.in);
    void methodname(){
        int priceLocation = input.nextInt();
    } 
}

Or if you want to define input inside the method

class myclass{
    void methodname(){
        Scanner input = new Scanner(System.in); // you can make this a final variable if you want
        int priceLocation = input.nextInt();
    }
}


来源:https://stackoverflow.com/questions/19947636/getting-error-while-using-nextint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!