2016-09-19 154 views
1

我有一個遊戲,其中兩個玩家輪流猜測一個已經隨機生成的數字。我使用的方法來控制播放器將如下:Java遊戲與玩家的死代碼

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

的問題是,該代碼被標記爲在Eclipse死代碼:

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

和:

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

我發現了類似的問題,但不能將它們應用於這個特定的應用程序。任何幫助,將不勝感激。

+0

提示:瞭解Java的命名約定。方法名稱go camelCase。所以變量名稱! – GhostCat

回答

5

player1lives and player2lives are final,所以他們永遠不能改變。他們都設置爲value = 4,這意味着他們絕不可能等於0

這裏:

int lives = player2lives; 
lives--; 

你正在改變一個生命值。它不會影響player2lives的值。

您應該將聲明更改爲:

private static int player1lives = 4; 

,然後會有沒有必要的生活變化:

player1lives--;