我有一个游戏,其中两个玩家轮流猜测一个随机生成的数字。我使用方法来控制玩家的转弯如下:
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 :(得分:5)
/user/profile
和player1lives
为player2lives
,因此永远无法更改。它们设置为final
,这意味着它们永远不会等于0。
下面:
value = 4
您正在改变生活价值。它不会影响int lives = player2lives;
lives--;
值。
您应该将声明更改为:
player2lives
然后就不需要生命变量:
private static int player1lives = 4;