user1953907
user1953907

Reputation: 323

Getting error while using .nextInt()

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();

Upvotes: 0

Views: 1644

Answers (3)

Ankit Rustagi
Ankit Rustagi

Reputation: 5637

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();
    }
}

Upvotes: 0

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35587

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.
}

Upvotes: 0

Rahul
Rahul

Reputation: 45090

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();

Upvotes: 2

Related Questions