2013-03-18 27 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例外。