简体   繁体   中英

Variable has already been defined in my method, or has it?

Consider the following method

public static boolean choosePlayer()
{
   String whatPlayer = input("Are you Player 1 or Player 2?");
   boolean player1;
   if (whatPlayer.equalsIgnoreCase("Player 1"))
   {
       boolean player1 = true;
   }    
   else
   {
       boolean player1 = false;
   }  
   return player1;
}   

I simply want this method to find out if the user is indeed player 1 and give me back player1 as true and false if they are not player 1. I get the compiler error

variable player1 is already defined in method choosePlayer()

If I remove the line of code boolean player1 , then it complains that it can't find the variable player1 .

I know I'm missing something simple but my brain is in mush-mode and it would be awesome if someone could point out my blunder. Thanks

The second declaration of player1 applies only inside the if statements, so you should keep only the first declaration.

public static boolean choosePlayer()
{
   String whatPlayer = input("Are you Player 1 or Player 2?");
   boolean player1;
   if (whatPlayer.equalsIgnoreCase("Player 1"))
   {
       player1 = true;
   }    
   else
   {
       player1 = false;
   }  
   return player1;
} 

Of course you can reduce this code to :

public static boolean choosePlayer()
{
   String whatPlayer = input("Are you Player 1 or Player 2?");
   return whatPlayer.equalsIgnoreCase("Player 1");
} 

or even

public static boolean choosePlayer()
{
   return input("Are you Player 1 or Player 2?").equalsIgnoreCase("Player 1");
} 

So you don't need that variable at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM