我是編程新手,所以我很抱歉如果有一個非常簡單的答案,但我似乎無法找到任何實際的東西。我正在使用一個掃描器對象來猜測你的數字遊戲中的用戶輸入。掃描程序在我的主要方法中聲明,並將用於其他一個方法中(但該方法將在整個地方調用)。在方法中使用掃描器
我試過聲明它是靜態的,但eclipse有一個適合,並且不會運行。
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;
}
這實際上也解決了我在幾種方法中使用的隨機生成器的問題 –