我在我的CardGames类中创建了一个简单的方法,它复制了一个纸牌游戏来玩条件语句。我从一个单独的Player类调用该方法,因为玩家根据卡获得/失去积分。我希望该方法能够更改播放器对象点变量。
我想要发生的是当Player对象调用playSimpleCardGame时,该方法会更改Player对象的点。
但是当我运行它时,积分不会改变。我试过扩展/实施这两个课程(即在黑暗中拍摄)。我还在CardGames类中创建了一个实例变量点,但随后Player对象没有将点作为变量。我错过了什么?
public class Player
{
private int points;
public static void main(String[] args)
{
CardGames steve = new CardGames();
System.out.println(steve.playSimpleCardGame("red"));
System.out.println(steve.playSimpleCardGame("red"));
System.out.println(steve.playSimpleCardGame("black"));
System.out.println(steve.playSimpleCardGame("black"));
System.out.println(steve.points);
}
}
public class CardGames
{
/*
* Rules of this game:
* If you draw a red card, you get a point.
* If you draw a black card, you lose two points.
*/
public int playSimpleCardGame(String color)
{
if (color.equalsIgnoreCase("red"))
return points = points + 1;
else
return points = points - 2;
}
}
public class Player
{
private int points;
public Player(){
points=0;
}
public static void main(String[] args)
{
CardGames game = new CardGames();
Player steve = new Player();
System.out.println(game.playSimpleCardGame("red", steve));
System.out.println(game.playSimpleCardGame("red", steve));
System.out.println(game.playSimpleCardGame("black", steve));
System.out.println(game.playSimpleCardGame("black", steve));
System.out.println(steve.points);
}
public int getPoints() {
return points;
}
public void addPoints(int p) {
this.points = points + p;
}
}
public class CardGames
{
/*
* Rules of this game:
* If you draw a red card, you get a point.
* If you draw a black card, you lose two points.
*/
public int playSimpleCardGame(String color, Player player)
{
if (color.equalsIgnoreCase("red"))
{
player.addPoints(1);
return player.getPoints();
}
else
{
player.addPoints(-2);
return player.getPoints();
}
}
}
答案 0 :(得分:-1)
首先,没有必要通过Player类扩展CardGames类。其次,即使你想这样做,也会是一个糟糕的设计。我不会进入设计部分。以下代码应该可以解答您的问题:
public class Player
{
public Integer points;
public Player(){
points=0;
}
public static void main(String[] args)
{
CardGames game = new CardGames();
Player steve = new Player();
System.out.println(game.playSimpleCardGame("red", steve));
System.out.println(game.playSimpleCardGame("red", steve));
System.out.println(game.playSimpleCardGame("black", steve));
System.out.println(game.playSimpleCardGame("black", steve));
System.out.println(steve.points);
}
}
public class CardGames
{
/*
* Rules of this game:
* If you draw a red card, you get a point.
* If you draw a black card, you lose two points.
*/
public int playSimpleCardGame(String color, Player player)
{
if (color.equalsIgnoreCase("red"))
return player.points = player.points + 1;
else
return player.points = player.points - 2;
}
}