Nicholas Gawley Nicholas Gawley - 2 months ago 16
Java Question

dead code in java game with player

I have a game in which two players take turns to guess a number that has been randomly generated. I'm using methods to control the player turns as follows:

import java.util.Random;
import javax.swing.JOptionPane;

public class randomnumgame {

private static final int player1lives = 4;
private static final int player2lives = 4;
public static void main(String []args){
while( player1lives > 0 && player2lives > 0){
playerturn1();
playerturn2();
if (player1lives == 0 || player2lives == 0){
game();
}
}
}
public static void playerturn2() {
int lives = player2lives;
Random rand = new Random();
int random = rand.nextInt(250) + 1;
String player2 = JOptionPane.showInputDialog
("Please enter a number between 1 and 250, Player 2.");
int player2int = Integer.parseInt(player2);
if(player2int == random){
JOptionPane.showMessageDialog(null, "Player 2 has guessed correctly. You have " +lives+ " lives left");
}
lives--;
JOptionPane.showMessageDialog(null, "Your guess was wrong. The actual number was: " +random+ " You have " +lives+ " left" );
}
public static void playerturn1() {
int lives = player1lives;
Random rand = new Random();
int random = rand.nextInt(250) + 1;
String player1 = JOptionPane.showInputDialog
("Please enter a number between 1 and 250, Player 1.");
int player1int = Integer.parseInt(player1);
if(player1int == random){
JOptionPane.showMessageDialog(null, "Player 1 has guessed correctly. You have " +lives+ " lives left");
}
lives--;
JOptionPane.showMessageDialog(null, "Your guess was wrong. The actual number was: " +random+ " You have " +lives+ " lives left");
}
private static void game(){
if(player1lives == 0){
JOptionPane.showMessageDialog(null, "Player 2 has won the game.");
System.exit(0);
}
if(player2lives == 0 ){
JOptionPane.showMessageDialog(null, "Player 1 has won the game.");
System.exit(0);
}
}
}


The problem is that this code is marked as dead code in Eclipse:

if (player1lives == 0 || player2lives == 0){
game();
}


And:

private static void game(){
if(player1lives == 0){
JOptionPane.showMessageDialog(null, "Player 2 has won the game.");
System.exit(0);
}
if(player2lives == 0 ){
JOptionPane.showMessageDialog(null, "Player 1 has won the game.");
System.exit(0);
}


I've found similar questions but can't apply them to this specific application. Any help would be appreciated.

Answer

player1lives and player2lives are final, so they never can be changed. They are set up to value = 4, that means that they never could be equal to 0.

Here:

int lives = player2lives;
lives--;

You are changing a lives value. It will not affect player2lives value.

You should change your declaration to:

private static int player1lives = 4;

and then there will be no need for lives variable :

player1lives--;