2013-04-12 41 views
2

我是編程新手,所以我很抱歉如果有一個非常簡單的答案,但我似乎無法找到任何實際的東西。我正在使用一個掃描器對象來猜測你的數字遊戲中的用戶輸入。掃描程序在我的主要方法中聲明,並將用於其他一個方法中(但該方法將在整個地方調用)。在方法中使用掃描器

我試過聲明它是靜態的,但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; 
} 
+0

這實際上也解決了我在幾種方法中使用的隨機生成器的問題 –

回答

4

你之所以看到這些錯誤是dataIn當地main方法,這意味着沒有其他方法可以訪問它,除非你明確地傳遞掃描儀那個方法。

有解決它的方法有兩種:

  • 傳遞掃描儀的DataTest方法,或
  • 結交類掃描儀static

這裏是你如何可以通過掃描儀:

public static int DataTest(int selectionBound, Scanner dataIn) ... 

這裏是你如何可以使Scanner靜:與

static Scanner dataIn = new Scanner(System.in); 
更換

Scanner dataIn = new Scanner(System.in); 

main()

main方法。

+0

「讓掃描儀在課堂上是靜態的」我想你的意思是「讓掃描儀成爲課堂上的靜態屬性」。 – ddmps

+0

@Pescis我用例子擴展了答案。 – dasblinkenlight

+0

這非常棒,謝謝 –

1

您不能訪問在其他方法中聲明的變量,甚至是主方法。這些變量有方法範圍這意味着它們根本不存在於聲明它們的方法之外。您可以通過將Scanner的聲明移到所有方法之外來解決此問題。這樣就可以享受課堂範圍,並可以在您的主課堂中的任何地方使用。

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*/ 
} 

由於在java中一般的經驗法則,變量不存在於他們所宣稱的最小對{}(唯一的例外是限定類的機構{})外:

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 
     } 
}