Reputation: 3764
I'm new to programming, so I apologize if there is a very simple answer to this, but I cannot seem to find anything that actually. I am using a scanner object for user input in a guess your number game. The scanner is declared in my main method, and will be used in a single other method (but that method will be called all over the place).
I've tried declaring it as static, but eclipse has a fit over that and won't run.
public static void main(String[] args) {
int selection = 0;
Scanner dataIn = new Scanner(System.in);
Random generator = new Random();
boolean willContinue = true;
while (willContinue)
{
selection = GameList();
switch (selection){
case 1: willContinue = GuessNumber(); break;
case 2: willContinue = GuessYourNumber(); break;
case 3: willContinue = GuessCard(); break;
case 4: willContinue = false; break;
}
}
}
public static int DataTest(int selectionBound){
while (!dataIn.hasNextInt())
{
System.out.println("Please enter a valid value");
dataIn.nextLine();
}
int userSelection = dataIn.nextInt;
while (userSelection > selectionBound || userSelection < 1)
{
System.out.println("Please enter a valid value from 1 to " + selectionBound);
userSelection = dataIn.nextInt;
}
return userSelection;
}
Upvotes: 4
Views: 37553
Reputation: 14313
You can't access variables declared in other methods, even the main method. These variables have method scope meaning that they simply do not exist outside of the method in which they are declared. you can fix this by moving the declaration of Scanner outside of all of your methods. This way it will enjoy class scope and can be used anywhere within your main class.
class Main{
//this will be accessable from any point within class Main
private static Scanner dataIn = new Scanner(System.in);
public static void main(String[] args){ /*stuff*/ }
/*Other methods*/
}
As a general rule of thumb in java, variables do not exists outside the smallest pair of {}
in which they were declared (the sole exception being the {}
that define the bodies of classes):
void someMethod()
{
int i; //i does not exist outside of someMethod
i = 122;
while (i > 0)
{
char c; //c does not exist outside of the while loop
c = (char) i - 48;
if (c > 'A')
{
boolean upperCase = c > 90; //b does not exist outside of the if statement
}
}
{
short s; //s does not exist outside of this random pair of braces
}
}
Upvotes: 2
Reputation: 726579
The reason why you see these errors is that dataIn
is local to the main
method, meaning that no other method can access it unless you explicitly pass the scanner to that method.
There are two ways of resolving it:
DataTest
method, orstatic
in the class.Here is how you can pass the scanner:
public static int DataTest(int selectionBound, Scanner dataIn) ...
Here is how you can make the Scanner
static: replace
Scanner dataIn = new Scanner(System.in);
in the main()
with
static Scanner dataIn = new Scanner(System.in);
outside the main
method.
Upvotes: 8