Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 239
Rush W. Avatar asked Sep 18 '14 15:09

Rush W.


People also ask

Can you convert Scanner to string?

toString() method returns the string representation of this Scanner. The string representation of a Scanner contains information that may be useful for debugging. The exact format is unspecified.


1 Answers

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);
like image 123
Elliott Frisch Avatar answered Oct 06 '22 00:10

Elliott Frisch