Search code examples
javaobjectstaticglobal-variablesjava.util.scanner

how to make scanner object as static


how can i refer to Scanner object which is defined globally from a static method(say main() ).. That is, how to make Scanner object as static.

Program (# for reference to my problem) :

import java.util.Scanner;

class spidy {

    Scanner input = new Scanner(System.in);             /*DECLARING SCANNER OBJECT OUTSIDE MAIN METHOD i.e Static method */


    public static void main(String args[]) {

        System.out.println("Enter a number");
        int n = input.nextInt();
    }
}

Error: non static variable input cannot be referenced from the static content


Solution

  • I had faced a similar doubt while solving a problem on Static Initializer Block. And there is a simple solution to it.

    Write as:

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

    Instead of :

    Scanner input = new Scanner(System.in);