Utilizing a Scanner inside a method
input, java, methods
Solution
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:
- Passing the scanner to the `DataTest` method, or
- Making the scanner `static` 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.
Problem
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; } ```