2013-03-18 74 views
-1

我有下面的代碼,我得到一個無法訪問的語句錯誤被拋出。這條線在它說它是罪魁禍首後有一條評論。無法訪問的聲明 - 爲什麼在這裏?

public static void selectPlayer() 
{ 
    // Loops through Player class' static array. If an index is storing a player object then print the player name out with a number for selection. 
    for(int i=0; 1<101; i++) 
    { 
     if (Player.playerArray[i] != null) 
     { 
      System.out.println(i + ". " + Player.playerArray[i - 1].playerName); 
     } 

     System.out.print("\nPlease enter the number that corresponds to the player you wish to use; "); // This line is where it failed to compile a la unreachable statement. 
     Scanner scanner = new Scanner(System.in); 
     // Take players selection and minus 1 so that it matches the Array index the player should come from. 
     int menuPlayerSelection = scanner.nextInt() - 1; 
     // Offer to play a new game with selected player, view player's stats, or exit. 
     System.out.print("You have selected " + Player.playerArray[menuPlayerSelection].playerName + ".\n1) Play\n2) View Score\n3) Exit?\nWhat do you want to do?: "); 
     int areYouSure = scanner.nextInt(); 
     // Check player's selection and run the corresponding method/menu 
     switch (areYouSure) 
     { 
      case 1: MainClass.playGame(menuPlayerSelection); break; 
      case 2: MainClass.viewPlayerScore(menuPlayerSelection); break; 
      case 3: MainClass.firstMenu(); break; 
      default: System.out.println("Invalid selection, please try again.\n"); 
         MainClass.firstMenu(); 
     } 
    } 

我的問題是,我該如何解決它?我得到爲什麼通常會出現無法訪問的聲明錯誤,但我無法弄清楚爲什麼它發生在我的情況。

+0

這種編碼風格是內嵌''後面的下一個邏輯步驟。爲什麼不使用內聯'}' – 2013-03-18 15:38:04

+0

一個右括號缺少(}),但也許它只是stackoverflow的編輯器... – mfo 2013-03-18 15:42:34

回答

7

先編輯一下。

for(int i=0; 1<101; i++) { 

這是無限循環。

因此,在您的for循環的條件設定,而不是我1

for(int i=0; i<101; i++){ 
+0

我不能相信我錯過了。看起來很難看到我和字體1之間的區別。歡呼,非常感謝。 – 2013-03-18 15:45:20

+0

@RudiKershaw您還忘記關閉for循環托架。 – 2013-03-18 15:45:52

+0

雖然這是正確的,但這並不能解釋爲什麼這條線被認爲無法到達。 – overthink 2013-03-18 15:46:25

2

的樣子。它永遠不會結束。

+1

但是1總是小於101,所以條件總是如此 - >無限循環。 – 2013-03-18 15:37:28

1
for(int i=0; 1<101; i++) 

應該

for(int i=0; i<101; i++) 

你的條件是1 < 101。無限循環永遠是真的。

0

你有for(int i=0; 1<101; i++)這是一個無限循環(因爲1總是低於101)。

1

代碼缺少},肯定會導致它打破

和其他人所說的,你的循環

for(int i=0; 1<101; i++) 

一定能滿足它的條件,它看起來你開始獲得IndexOutOfBound例外。

相關問題