Rush W.
Rush W.

Reputation: 1361

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

Upvotes: 5

Views: 45981

Answers (3)

Elliott Frisch
Elliott Frisch

Reputation: 201447

If I understand your question, then you could change this

Scanner input = new Scanner(System.in);

to (visible to all other classes - you said global)

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

or (visible to the current class - any other static method (main() in your case) )

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

Upvotes: 9

Suthan Srinivasan
Suthan Srinivasan

Reputation: 129

Just use static keyword before Scanner class.

Example:

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

By using the scan object we refer anywhere in the code

Upvotes: 3

adityaekawade
adityaekawade

Reputation: 312

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

Upvotes: 5

Related Questions