gpt4 book ai didi

java - Java 游戏中的死代码与玩家

转载 作者:行者123 更新时间:2023-11-29 07:32:55 24 4
gpt4 key购买 nike

我有一个游戏,两个玩家轮流猜一个随机生成的数字。我正在使用如下方法来控制玩家转弯:

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

我发现了类似的问题,但无法将它们应用到这个特定的应用程序中。任何帮助将不胜感激。

最佳答案

player1livesplayer2livesfinal,因此永远无法更改。它们被设置为 value = 4,这意味着它们永远不会等于 0。

这里:

int lives = player2lives;
lives--;

你正在改变生命值。它不会影响 player2lives 值。

您应该将声明更改为:

private static int player1lives = 4;

然后就不需要 lives 变量了:

player1lives--;

关于java - Java 游戏中的死代码与玩家,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39579397/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com