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
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With