如何在三个 类 之间使用 setter 和 getter 传递值
How to pass values using setter and getter among three classes
我一直在练习一个 classical Nim 游戏的项目。我现在的成就是:
- 添加、删除、编辑、显示、播放器。 (Nimsys 和 NimPlayer)
- 选择两名玩家进行游戏。 (NimGame class)
每次游戏结束的时候,我都需要return这两个东西从NimGame到NimPlayer。然后我可以在 Nimsys 中使用 getter:
- 如果玩家获胜,his/her得分+1。
- 每场比赛结束后,上场球员的比赛次数+1。
我已经尝试过将 "score" 和 "gamePlayed" 从 NimPlayer 传递到 NimGame,将 getter,一开始是 0,放在 setter 设置数字+1.
scores = NimPlayer.setScore(NimPlayer.getScore() + 1);
但是,我不知道如何将这里的"scores"传回给NimPlayer使用。我希望将分数传回给 NimPlayer。然后,我可以从 Nimsys 调用它。这是我的代码。
import java.util.Scanner;
public class Nimsys {
public static String[] splitName(String inName) {
String[] splittedLine = inName.split(",");
String[] name = null;
if (splittedLine.length==3) {
String userName = splittedLine[0].trim();
String familyName = splittedLine[1].trim();
String givenName = splittedLine[2].trim();
name = new String[3];
name[0] = userName;
name[1] = familyName;
name[2] = givenName;
}
return name;
}
public static String [] splitData(String dataIn) {
String[] splittedLine = dataIn.split(",");
String[] data = null;
if (splittedLine.length==4) {
String initialStone = splittedLine[0];
String stoneRemoval = splittedLine[1];
String player1 = splittedLine[2].trim();
String player2 = splittedLine[3].trim();
data = new String[4];
data[0] = initialStone;
data[1] = stoneRemoval;
data[2] = player1;
data[3] = player2;
}
return data;
}
public static String playerChecker(String name) {
String player = null;
for (int i = 0; i < NimPlayer.getId(); i++) {
player = NimPlayer.getPlayer()[i].getUserName();
if (player.equals(name)) {
break;
}
}
return player;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (true) {
System.out.print('$');
String commandin = in.next();
if (commandin.equals("addplayer")) {
String inName = in.nextLine();
String[] name = splitName(inName);
//Make sure the vadality of in name
//Can use playerCheck to simplify the code
if (name!=null && name.length==3) {
for (int i = 0; i < NimPlayer.getId(); i ++) {
String userCheck = NimPlayer.getPlayer()[i].getUserName();
if (userCheck.contains(name[0])) {
System.out.println("The player already exist");//Test if player has been created
}
}
NimPlayer.createPlayer(name[0], name[1], name[2], 0, 0);
System.out.println("The player has been created.");
} else {
System.out.println("Not Valid! Please enter again!");
}
}
if (commandin.equals("removeplayer")) {
//cannot loop through the entire null array, would be NullPointerException
String removeUserName = in.nextLine().trim();
/*System.out.println("Are you sure you want to remove all players? (y/n) \n");
//System.out.print('$');
commandin = in.next();
if (commandin.equals("y")) {
for (int i = 0; i < NimPlayer.getId(); i++) {
NimPlayer.getPlayer()[i] = null;
System.out.println("Remove all the players");
}
} else {
System.out.print('$');
}*/
//commandin = in.next();
for (int i = 0; i < NimPlayer.getId(); i++) {
String userName = NimPlayer.getPlayer()[i].getUserName().trim();
if (removeUserName != null && userName.equals(removeUserName)) {
NimPlayer.getPlayer()[i] = null;
System.out.println("Remove successfully!");// A test to see if the code runs
} else {
System.out.println("The player does not exist");
}
}
}
if (commandin.equals("editplayer")) {
String inName = in.nextLine();
String[] splittedLine = inName.split(",");
if (splittedLine!=null && splittedLine.length==3) {
String userName = splittedLine[0].trim();
String familyName = splittedLine[1].trim();
String givenName = splittedLine[2].trim();
//System.out.println(userName+","+familyName+","+givenName);//Test if in name in the if loop
for (int i = 0; i < NimPlayer.getId(); i++) {
String userCheck = NimPlayer.getPlayer()[i].getUserName().trim();
if (userName != null && userCheck.equals(userName)) {
NimPlayer.getPlayer()[i].setFamilyName(familyName);
NimPlayer.getPlayer()[i].setGivenName(givenName);
System.out.println("Edit successfully");
} else {
System.out.println("The player does not exist.");
}
}
} else {
System.out.println("Invalid in! Please enter again.");
}
}
if (commandin.equals("displayplayer")) {
String user = in.nextLine().trim();
for (int i = 0; i < NimPlayer.getId(); i++) {
String userCheck = NimPlayer.getPlayer()[i].getUserName().trim();
String userName = NimPlayer.getPlayer()[i].getUserName();
String familyName = NimPlayer.getPlayer()[i].getfamilyName();
String givenName = NimPlayer.getPlayer()[i].getGivenName();
int score = NimPlayer.setScore(NimPlayer.getScore());
int gamePlayed = NimPlayer.setGamePlayed(NimPlayer.getGamePlayed());
if (user != null && userCheck.equals(user)) {
System.out.println(userName+","+familyName+","+givenName+","+gamePlayed+" games,"+score +" wins");
}
}
}
if (commandin.equals("startgame")) {
String dataIn = null, player1 = null, player2 = null;
do {
dataIn = in.nextLine();
String [] data = splitData(dataIn);
if (data != null && data.length==4) {
player1 = playerChecker(data[2]);
player2 = playerChecker(data[3]);
NimGame game = new NimGame(data[0].trim(), data[1], player1, player2);
game.playGame(data[0].trim(), data[1], player1, player2);
}
} while(player1 == null || player2 == null);
}
}
}
}
以上是我Nimsys的主要方法。我在使用 displayplayer
命令调用这些值时遇到问题。应该是这样的:
userName,familyName,givenName,gamePlayed "games",score "wins"
下面是我的 NimPlayer class:
//username, given name, family name, number of game played, number of games won
public class NimPlayer {
private String userName;
private String familyName;
private String givenName;
private static int score;
private static int gamePlayed;
static int id;
static NimPlayer[] playerList = new NimPlayer[10]; // set an array here
//define NimPlayer data type
public NimPlayer(String userName, String surName, String givenName, int gamePlayed, int score) {
this.userName = userName;
this.familyName = surName;
this.givenName = givenName;
NimPlayer.score = score;
NimPlayer.gamePlayed = gamePlayed;
}
// create new data using NimPlayer data type
public static void createPlayer(String userName, String familyName, String givenName, int gamePlayed, int score) {
if (id<10) {
playerList[id++] = new NimPlayer(userName, familyName, givenName, gamePlayed, score);
} else {
System.out.println("Cannot add more players.");
}
}
public static int getId() {
return id;
}
public static NimPlayer [] getPlayer() {
return playerList;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
public void setGivenName(String givenName) {
this.givenName = givenName;
}
public String getUserName() {
return userName;
}
public String getfamilyName() {
return familyName;
}
public String getGivenName() {
return givenName;
}
public static int setScore(int score) {
return score;
}
public static int getScore() {
return score;
}
public static int setGamePlayed (int gamePlayed) {
return gamePlayed;
}
public static int getGamePlayed() {
return gamePlayed;
}
}
最后是 NimGame 部分:
import java.util.Scanner;
//playing process
//current stone count
//upper bound on stone removal
//two players
public class NimGame {
private static int gamePlayed;
private static int scores;
String player1;
String player2;
String playOrNot;
String initialStoneInput;
String dataRemoval;
int stars;
int stoneBalance;
int initialStone;
int upperBound;
public int initializeStone(int startStones) {
stoneBalance = startStones;
return stoneBalance;
}
public void removeStones(int stonesTaken) {
int updatedBalance = stoneBalance - stonesTaken;
stoneBalance = updatedBalance;
}
public void printStar(int star) {
stars = star;
stars = stoneBalance;
for (int stars = 1; stars <= star; stars++) {
System.out.print(" *");
}
System.out.println();
}
public static int earnPoint(String player) {
for (int i = 0; i < NimPlayer.getId(); i++) {
String playerCheck = NimPlayer.getPlayer()[i].getUserName();
if (playerCheck.equals(player)) {
scores = NimPlayer.setScore(NimPlayer.getScore() + 1);
}
}
return scores;
}
public static int gamePlayed(String player) {
for (int i = 0; i < NimPlayer.getId(); i++) {
String playerCheck = NimPlayer.getPlayer()[i].getUserName();
if (playerCheck.equals(player)) {
gamePlayed = NimPlayer.setGamePlayed(NimPlayer.getGamePlayed() + 1);
}
}
return gamePlayed + 1;
}
public int getGameScore() {
return scores;
}
public int getNumberGamePlayed() {
return gamePlayed;
}
public NimGame (String initialStone ,String dataRemoval,String player1, String player2) {
this.initialStoneInput = initialStone;
this.dataRemoval = dataRemoval;
this.player1 = player1;
this.player2 = player2;
}
Scanner in = new Scanner(System.in);
public void playGame (String initialStone ,String dataRemoval,String player1, String player2) {
//Convert user input string into integer
int initialStoneInt = Integer.parseInt(initialStoneInput);
initializeStone(initialStoneInt);
int upperBound = Integer.parseInt(dataRemoval);
System.out.println("Initial stone count: "+initialStoneInt);
System.out.println("Maximum stone removal: "+dataRemoval);
System.out.println("Player 1: "+player1);
System.out.println("Player 2: "+player2);
do {
// while stoneBalance > 0, two players keep playing the game
while (stoneBalance > 0) {
// player1's turn and remove the stones; decision of winning
System.out.println(player1 + "'s turn - remove how many?\n");
int takeStone = in.nextInt();
while (takeStone > upperBound || takeStone <= 0) {
System.out.println(
"Invalid, you need to remove stones under upper "+
"bound limit or above 0. \n Please enter again.");
takeStone = in.nextInt();
}
removeStones(takeStone); //remove the stone
if (stoneBalance > 0) {
//show the remaining stones
System.out.print(stoneBalance + " stones left:");
printStar(stoneBalance);
} else if (stoneBalance <= 0) {
System.out.println("Game Over\n" + player2 + " wins!\n");
earnPoint(player2);
break;
}
// player2's turn and remove the stones; decision of winning
System.out.println(player2 + "'s turn - remove how many?\n");
takeStone = in.nextInt();
while (takeStone > upperBound || takeStone <= 0) {
System.out.println(
"Invalid, you need to remove stones under upper " +
"bound limit or above 0. \n Please enter again.");
takeStone = in.nextInt();
}
removeStones(takeStone);
if (stoneBalance > 0) {
System.out.print(stoneBalance + " stones left:");
printStar(stoneBalance);
} else if (stoneBalance <= 0) {
System.out.println("Game Over\n" + player1 + " wins!\n");
earnPoint(player1);
break;
}
}
// ask players to play again
//in.nextLine();
System.out.println("Do you want to play again (Y/N):");
playOrNot = in.nextLine();
gamePlayed(player1);
gamePlayed(player2);
} while (playOrNot.equals("Y"));
}
}
您的代码中需要解决以下问题:
- 由于您正在使用
createPlayer
创建一个 NimPlayer
,请创建以下构造函数 private
并 创建一个私有的无参数构造函数 所以除了使用 createPlayer
来创建 NimPlayer
. 别无他法
改为:
private NimPlayer(String userName, String surName, String givenName) {
this.userName = userName;
this.familyName = surName;
this.givenName = givenName;
}
- 从
createPlayer
中删除参数int gamePlayed
和int score
,因为当您创建NimPlayer
时,播放器没有gamePlayed
的任何数据和 score
。这些东西会在游戏过程中设置。
改为:
public static void createPlayer(String userName, String familyName, String givenName) {
if (id<10) {
playerList[id++] = new NimPlayer(userName, familyName, givenName);
} else {
System.out.println("Cannot add more players.");
}
}
- 由于
score
和 gamePlayed
属于个人玩家,即每个个人玩家将拥有 his/her score
和 gamePlayed
独立于其他玩家,这些属性需要是非静态的。只有当变量的值对于所有实例都应该相同时,才应该创建一个 static
变量,例如NimPlayer[] playerList
或 id
。请注意,我之前曾要求您使用名称 counter
而不是 id
,因为它应该是编号的计数器。球员的名字,id
令人困惑。如果您想为个别玩家创建一个 id
字段,请使用 IDE 的 Replace All
功能将所有出现的 id
替换为 counter
,所有出现Id
与 Counter
(用于替换 getter 和 setter),然后在 [=15= 中创建一个非静态 private int id;
,如 firstName
、familyName
等].
声明 score
和 gamePlayed
如下:
private int score;
private int gamePlayed;
//public getters and setters of score and gamePlayed
score
和 gamePlayed
应该按照访问名称的方式访问
if (commandin.equals("displayplayer")) {
String user = in.nextLine().trim();
NimPlayer [] players = NimPlayer.getPlayer();
for (int i = 0; i < NimPlayer.getId(); i++) {
String userCheck = players[i].getUserName().trim();
String userName = players[i].getUserName();
String familyName = players[i].getFamilyName();
String givenName = players[i].getGivenName();
int score = players[i].getScore();
int gamePlayed = players[i].getGamePlayed();
if (user != null && userCheck.equals(user)) {
System.out.println(userName + "," + familyName + "," + givenName + "," + gamePlayed + " games,"
+ score + " wins");
}
}
}
score
的值应该设为
public static int earnPoint(String player) {
int i = 0;
for (i = 0; i < NimPlayer.getCounter(); i++) {
String playerCheck = NimPlayer.getPlayer()[i].getUserName();
if (playerCheck.equals(player)) {
NimPlayer.getPlayer()[i].setScore(NimPlayer.getPlayer()[i].getScore() + 1);
break;
}
}
return NimPlayer.getPlayer()[i].getScore();
}
我完全修改了您的模型代码,这使得其余代码更加简单。创建良好的应用程序模型会使创建应用程序的其余部分变得更加容易。
这是您修改后的 NimPlayer
class。构成这个class的字段都与游戏玩家有关
class 仅由 getter 和 setter 组成。两个设置器添加而不是替换。 class.
中没有静态字段
public class NimPlayer {
private final int id;
private final String userName;
private String familyName;
private String givenName;
private int gamesPlayed;
private int gamesWon;
public NimPlayer(int id, String userName, String familyName,
String givenName) {
this.id = id;
this.userName = userName;
this.familyName = familyName;
this.givenName = givenName;
this.gamesPlayed = 0;
this.gamesWon = 0;
}
public int getId() {
return id;
}
public String getUserName() {
return userName;
}
public String getFamilyName() {
return familyName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
public String getGivenName() {
return givenName;
}
public void setGivenName(String givenName) {
this.givenName = givenName;
}
public int getGamesPlayed() {
return gamesPlayed;
}
public void addGamePlayed() {
this.gamesPlayed++;
}
public int getGamesWon() {
return gamesWon;
}
public void addGamesWon() {
this.gamesWon++;
}
}
我新建了一个class,NimModel
来保存游戏状态。 class 是 playerList
以及与 playerList
关联的所有代码所在的位置。
将 playerList
设为 List
会简化代码,但我将 playerList
保留为数组,以向您展示在数组中添加和删除玩家所涉及的代码。
public class NimModel {
private int numberOfPlayers;
private int limit;
private NimPlayer[] playerList;
public NimModel() {
this.numberOfPlayers = 0;
this.limit = 10;
this.playerList = new NimPlayer[limit];
}
public boolean createPlayer(String userName, String familyName,
String givenName) {
if (numberOfPlayers < limit) {
int id = getFirstPlayerSlot();
if (id >= 0) {
playerList[id] = new NimPlayer(id,
userName, familyName, givenName);
numberOfPlayers++;
}
return true;
} else {
return false;
}
}
private int getFirstPlayerSlot() {
for (int i = 0; i < limit; i++) {
if (playerList == null) {
return i;
}
}
return -1;
}
public NimPlayer getPlayer(int id) {
return playerList[id];
}
public NimPlayer getPlayer(String userName) {
for (int i = 0; i < limit; i++) {
if (playerList[i] != null) {
if (userName.equals(playerList[i].getUserName())) {
return playerList[i];
}
}
}
return null;
}
public NimPlayer removePlayer(String userName) {
for (int i = 0; i < limit; i++) {
NimPlayer player = playerList[i];
if (player != null) {
if (userName.equals(player.getUserName())) {
this.playerList[i] = null;
numberOfPlayers--;
return player;
}
}
}
return null;
}
public int getNumberOfPlayers() {
return numberOfPlayers;
}
}
最后,这是您修改后的 Nimsys
和 NimGame
class。同样,我们删除了所有静态引用。
如果您按照方法的调用顺序编写代码,它会使代码更易于阅读和理解。也就是说,先提要点,再提细节。
import java.util.Scanner;
public class Nimsys {
private NimModel nimModel;
public static void main(String[] args) {
Nimsys nimsys = new Nimsys();
nimsys.processCommands();
}
private void processCommands() {
this.nimModel = new NimModel();
Scanner in = new Scanner(System.in);
while (true) {
System.out.print('$');
String commandin = in.nextLine().trim();
if (commandin.equalsIgnoreCase("addplayer")) {
addPlayer(in);
}
if (commandin.equalsIgnoreCase("removeplayer")) {
removePlayer(in);
}
if (commandin.equalsIgnoreCase("editplayer")) {
editPlayer(in);
}
if (commandin.equalsIgnoreCase("displayplayer")) {
displayPlayer(in);
}
if (commandin.equalsIgnoreCase("startgame")) {
startGame(in);
}
}
}
private void addPlayer(Scanner in) {
String inName = in.nextLine().trim();
String[] name = splitName(inName);
if (name != null && name.length == 3) {
NimPlayer player = nimModel.getPlayer(name[0]);
if (player == null) {
nimModel.createPlayer(name[0], name[1], name[2]);
System.out.println("The player has been created.");
} else {
System.out.println("The player is already in "
+ "the list.");
}
} else {
System.out.println("Not Valid! Please enter again!");
}
}
private String[] splitName(String inName) {
String[] splittedLine = inName.split(",");
String[] name = null;
if (splittedLine.length == 3) {
String userName = splittedLine[0].trim();
String familyName = splittedLine[1].trim();
String givenName = splittedLine[2].trim();
name = new String[3];
name[0] = userName;
name[1] = familyName;
name[2] = givenName;
}
return name;
}
private void removePlayer(Scanner in) {
String removeUserName = in.nextLine().trim();
NimPlayer player = nimModel.removePlayer(removeUserName);
if (player == null) {
System.out.println("The player does not exist");
} else {
System.out.println("Player " + player.getUserName() +
" removed successfully!");
}
}
private void editPlayer(Scanner in) {
String inName = in.nextLine().trim();
String[] splittedLine = inName.split(",");
if (splittedLine != null && splittedLine.length == 3) {
String userName = splittedLine[0].trim();
String familyName = splittedLine[1].trim();
String givenName = splittedLine[2].trim();
NimPlayer player = nimModel.getPlayer(userName);
if (player == null) {
System.out.println("The player does "
+ "not exist.");
} else {
player.setFamilyName(familyName);
player.setGivenName(givenName);
System.out.println("Edited successfully");
}
} else {
System.out.println("Invalid user name! Please "
+ "enter again.");
}
}
private void displayPlayer(Scanner in) {
String userName = in.nextLine().trim();
NimPlayer player = nimModel.getPlayer(userName);
String familyName = player.getFamilyName();
String givenName = player.getGivenName();
int gamesWon = player.getGamesWon();
int gamesPlayed = player.getGamesPlayed();
System.out.println(userName + "," + familyName +
"," + givenName + "," + gamesPlayed +
" games," + gamesWon + " wins");
}
private void startGame(Scanner in) {
NimPlayer player1 = null, player2 = null;
do {
String dataIn = in.nextLine().trim();
String[] data = splitData(dataIn);
if (data != null && data.length == 4) {
player1 = nimModel.getPlayer(data[2]);
player2 = nimModel.getPlayer(data[3]);
NimGame game = new NimGame(nimModel, data[0],
data[1], player1, player2);
game.playGame();
}
} while (player1 == null || player2 == null);
}
private String[] splitData(String dataIn) {
String[] splittedLine = dataIn.split(",");
String[] data = null;
if (splittedLine.length == 4) {
String initialStone = splittedLine[0];
String stoneRemoval = splittedLine[1];
String player1 = splittedLine[2].trim();
String player2 = splittedLine[3].trim();
data = new String[4];
data[0] = initialStone;
data[1] = stoneRemoval;
data[2] = player1;
data[3] = player2;
}
return data;
}
}
NimGame class
import java.util.Scanner;
public class NimGame {
NimPlayer player1;
NimPlayer player2;
String playOrNot;
String initialStoneInput;
String dataRemoval;
int stars;
int stoneBalance;
int initialStone;
int upperBound;
public NimGame(NimModel nimModel, String initialStoneInput,
String dataRemoval,
NimPlayer player1, NimPlayer player2) {
this.initialStoneInput = initialStoneInput;
this.dataRemoval = dataRemoval;
this.player1 = player1;
this.player2 = player2;
}
Scanner in = new Scanner(System.in);
public void playGame() {
// Convert user input string into integer
int initialStoneInt = Integer.parseInt(initialStoneInput);
initializeStone(initialStoneInt);
int upperBound = Integer.parseInt(dataRemoval);
System.out.println("Initial stone count: " +
initialStoneInt);
System.out.println("Maximum stone removal: " +
dataRemoval);
System.out.println("Player 1: " + player1.getUserName());
System.out.println("Player 2: " + player2.getUserName());
do {
// while stoneBalance > 0, two players
// keep playing the game
while (stoneBalance > 0) {
// player1's turn and remove the stones;
// decision of winning
System.out.println(player1.getUserName() + "'s "
+ "turn - remove how many?\n");
int takeStone = in.nextInt();
while (takeStone > upperBound ||
takeStone <= 0) {
System.out.println("Invalid, you need "
+ "to remove stones under upper "
+ "bound limit or above 0. \n"
+ "Please enter again.");
takeStone = in.nextInt();
}
removeStones(takeStone); // remove the stone
if (stoneBalance > 0) {
// show the remaining stones
System.out.print(stoneBalance +
" stones left:");
printStar(stoneBalance);
} else if (stoneBalance <= 0) {
System.out.println("Game Over\n" +
player2.getUserName() + " wins!\n");
earnPoint(player2);
break;
}
// player2's turn and remove the stones;
// decision of winning
System.out.println(player2.getUserName() + "'s "
+ "turn - remove how many?\n");
takeStone = in.nextInt();
while (takeStone > upperBound ||
takeStone <= 0) {
System.out.println("Invalid, you need "
+ "to remove stones under upper "
+ "bound limit or above 0. \n"
+ "Please enter again.");
takeStone = in.nextInt();
}
removeStones(takeStone);
if (stoneBalance > 0) {
System.out.print(stoneBalance + " "
+ "stones left:");
printStar(stoneBalance);
} else if (stoneBalance <= 0) {
System.out.println("Game Over\n" +
player1.getUserName() + " wins!\n");
earnPoint(player1);
break;
}
}
player1.addGamePlayed();
player2.addGamePlayed();;
// ask players to play again
// in.nextLine();
System.out.println("Do you want to play "
+ "again (Y/N):");
playOrNot = in.nextLine().trim();
} while (playOrNot.equalsIgnoreCase("Y"));
}
public int initializeStone(int startStones) {
stoneBalance = startStones;
return stoneBalance;
}
public void removeStones(int stonesTaken) {
int updatedBalance = stoneBalance - stonesTaken;
stoneBalance = updatedBalance;
}
private void printStar(int star) {
stars = star;
stars = stoneBalance;
for (int stars = 1; stars <= star; stars++) {
System.out.print(" *");
}
System.out.println();
}
private int earnPoint(NimPlayer player) {
player.addGamesWon();
return player.getGamesWon();
}
}
我一直在练习一个 classical Nim 游戏的项目。我现在的成就是:
- 添加、删除、编辑、显示、播放器。 (Nimsys 和 NimPlayer)
- 选择两名玩家进行游戏。 (NimGame class)
每次游戏结束的时候,我都需要return这两个东西从NimGame到NimPlayer。然后我可以在 Nimsys 中使用 getter:
- 如果玩家获胜,his/her得分+1。
- 每场比赛结束后,上场球员的比赛次数+1。
我已经尝试过将 "score" 和 "gamePlayed" 从 NimPlayer 传递到 NimGame,将 getter,一开始是 0,放在 setter 设置数字+1.
scores = NimPlayer.setScore(NimPlayer.getScore() + 1);
但是,我不知道如何将这里的"scores"传回给NimPlayer使用。我希望将分数传回给 NimPlayer。然后,我可以从 Nimsys 调用它。这是我的代码。
import java.util.Scanner;
public class Nimsys {
public static String[] splitName(String inName) {
String[] splittedLine = inName.split(",");
String[] name = null;
if (splittedLine.length==3) {
String userName = splittedLine[0].trim();
String familyName = splittedLine[1].trim();
String givenName = splittedLine[2].trim();
name = new String[3];
name[0] = userName;
name[1] = familyName;
name[2] = givenName;
}
return name;
}
public static String [] splitData(String dataIn) {
String[] splittedLine = dataIn.split(",");
String[] data = null;
if (splittedLine.length==4) {
String initialStone = splittedLine[0];
String stoneRemoval = splittedLine[1];
String player1 = splittedLine[2].trim();
String player2 = splittedLine[3].trim();
data = new String[4];
data[0] = initialStone;
data[1] = stoneRemoval;
data[2] = player1;
data[3] = player2;
}
return data;
}
public static String playerChecker(String name) {
String player = null;
for (int i = 0; i < NimPlayer.getId(); i++) {
player = NimPlayer.getPlayer()[i].getUserName();
if (player.equals(name)) {
break;
}
}
return player;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (true) {
System.out.print('$');
String commandin = in.next();
if (commandin.equals("addplayer")) {
String inName = in.nextLine();
String[] name = splitName(inName);
//Make sure the vadality of in name
//Can use playerCheck to simplify the code
if (name!=null && name.length==3) {
for (int i = 0; i < NimPlayer.getId(); i ++) {
String userCheck = NimPlayer.getPlayer()[i].getUserName();
if (userCheck.contains(name[0])) {
System.out.println("The player already exist");//Test if player has been created
}
}
NimPlayer.createPlayer(name[0], name[1], name[2], 0, 0);
System.out.println("The player has been created.");
} else {
System.out.println("Not Valid! Please enter again!");
}
}
if (commandin.equals("removeplayer")) {
//cannot loop through the entire null array, would be NullPointerException
String removeUserName = in.nextLine().trim();
/*System.out.println("Are you sure you want to remove all players? (y/n) \n");
//System.out.print('$');
commandin = in.next();
if (commandin.equals("y")) {
for (int i = 0; i < NimPlayer.getId(); i++) {
NimPlayer.getPlayer()[i] = null;
System.out.println("Remove all the players");
}
} else {
System.out.print('$');
}*/
//commandin = in.next();
for (int i = 0; i < NimPlayer.getId(); i++) {
String userName = NimPlayer.getPlayer()[i].getUserName().trim();
if (removeUserName != null && userName.equals(removeUserName)) {
NimPlayer.getPlayer()[i] = null;
System.out.println("Remove successfully!");// A test to see if the code runs
} else {
System.out.println("The player does not exist");
}
}
}
if (commandin.equals("editplayer")) {
String inName = in.nextLine();
String[] splittedLine = inName.split(",");
if (splittedLine!=null && splittedLine.length==3) {
String userName = splittedLine[0].trim();
String familyName = splittedLine[1].trim();
String givenName = splittedLine[2].trim();
//System.out.println(userName+","+familyName+","+givenName);//Test if in name in the if loop
for (int i = 0; i < NimPlayer.getId(); i++) {
String userCheck = NimPlayer.getPlayer()[i].getUserName().trim();
if (userName != null && userCheck.equals(userName)) {
NimPlayer.getPlayer()[i].setFamilyName(familyName);
NimPlayer.getPlayer()[i].setGivenName(givenName);
System.out.println("Edit successfully");
} else {
System.out.println("The player does not exist.");
}
}
} else {
System.out.println("Invalid in! Please enter again.");
}
}
if (commandin.equals("displayplayer")) {
String user = in.nextLine().trim();
for (int i = 0; i < NimPlayer.getId(); i++) {
String userCheck = NimPlayer.getPlayer()[i].getUserName().trim();
String userName = NimPlayer.getPlayer()[i].getUserName();
String familyName = NimPlayer.getPlayer()[i].getfamilyName();
String givenName = NimPlayer.getPlayer()[i].getGivenName();
int score = NimPlayer.setScore(NimPlayer.getScore());
int gamePlayed = NimPlayer.setGamePlayed(NimPlayer.getGamePlayed());
if (user != null && userCheck.equals(user)) {
System.out.println(userName+","+familyName+","+givenName+","+gamePlayed+" games,"+score +" wins");
}
}
}
if (commandin.equals("startgame")) {
String dataIn = null, player1 = null, player2 = null;
do {
dataIn = in.nextLine();
String [] data = splitData(dataIn);
if (data != null && data.length==4) {
player1 = playerChecker(data[2]);
player2 = playerChecker(data[3]);
NimGame game = new NimGame(data[0].trim(), data[1], player1, player2);
game.playGame(data[0].trim(), data[1], player1, player2);
}
} while(player1 == null || player2 == null);
}
}
}
}
以上是我Nimsys的主要方法。我在使用 displayplayer
命令调用这些值时遇到问题。应该是这样的:
userName,familyName,givenName,gamePlayed "games",score "wins"
下面是我的 NimPlayer class:
//username, given name, family name, number of game played, number of games won
public class NimPlayer {
private String userName;
private String familyName;
private String givenName;
private static int score;
private static int gamePlayed;
static int id;
static NimPlayer[] playerList = new NimPlayer[10]; // set an array here
//define NimPlayer data type
public NimPlayer(String userName, String surName, String givenName, int gamePlayed, int score) {
this.userName = userName;
this.familyName = surName;
this.givenName = givenName;
NimPlayer.score = score;
NimPlayer.gamePlayed = gamePlayed;
}
// create new data using NimPlayer data type
public static void createPlayer(String userName, String familyName, String givenName, int gamePlayed, int score) {
if (id<10) {
playerList[id++] = new NimPlayer(userName, familyName, givenName, gamePlayed, score);
} else {
System.out.println("Cannot add more players.");
}
}
public static int getId() {
return id;
}
public static NimPlayer [] getPlayer() {
return playerList;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
public void setGivenName(String givenName) {
this.givenName = givenName;
}
public String getUserName() {
return userName;
}
public String getfamilyName() {
return familyName;
}
public String getGivenName() {
return givenName;
}
public static int setScore(int score) {
return score;
}
public static int getScore() {
return score;
}
public static int setGamePlayed (int gamePlayed) {
return gamePlayed;
}
public static int getGamePlayed() {
return gamePlayed;
}
}
最后是 NimGame 部分:
import java.util.Scanner;
//playing process
//current stone count
//upper bound on stone removal
//two players
public class NimGame {
private static int gamePlayed;
private static int scores;
String player1;
String player2;
String playOrNot;
String initialStoneInput;
String dataRemoval;
int stars;
int stoneBalance;
int initialStone;
int upperBound;
public int initializeStone(int startStones) {
stoneBalance = startStones;
return stoneBalance;
}
public void removeStones(int stonesTaken) {
int updatedBalance = stoneBalance - stonesTaken;
stoneBalance = updatedBalance;
}
public void printStar(int star) {
stars = star;
stars = stoneBalance;
for (int stars = 1; stars <= star; stars++) {
System.out.print(" *");
}
System.out.println();
}
public static int earnPoint(String player) {
for (int i = 0; i < NimPlayer.getId(); i++) {
String playerCheck = NimPlayer.getPlayer()[i].getUserName();
if (playerCheck.equals(player)) {
scores = NimPlayer.setScore(NimPlayer.getScore() + 1);
}
}
return scores;
}
public static int gamePlayed(String player) {
for (int i = 0; i < NimPlayer.getId(); i++) {
String playerCheck = NimPlayer.getPlayer()[i].getUserName();
if (playerCheck.equals(player)) {
gamePlayed = NimPlayer.setGamePlayed(NimPlayer.getGamePlayed() + 1);
}
}
return gamePlayed + 1;
}
public int getGameScore() {
return scores;
}
public int getNumberGamePlayed() {
return gamePlayed;
}
public NimGame (String initialStone ,String dataRemoval,String player1, String player2) {
this.initialStoneInput = initialStone;
this.dataRemoval = dataRemoval;
this.player1 = player1;
this.player2 = player2;
}
Scanner in = new Scanner(System.in);
public void playGame (String initialStone ,String dataRemoval,String player1, String player2) {
//Convert user input string into integer
int initialStoneInt = Integer.parseInt(initialStoneInput);
initializeStone(initialStoneInt);
int upperBound = Integer.parseInt(dataRemoval);
System.out.println("Initial stone count: "+initialStoneInt);
System.out.println("Maximum stone removal: "+dataRemoval);
System.out.println("Player 1: "+player1);
System.out.println("Player 2: "+player2);
do {
// while stoneBalance > 0, two players keep playing the game
while (stoneBalance > 0) {
// player1's turn and remove the stones; decision of winning
System.out.println(player1 + "'s turn - remove how many?\n");
int takeStone = in.nextInt();
while (takeStone > upperBound || takeStone <= 0) {
System.out.println(
"Invalid, you need to remove stones under upper "+
"bound limit or above 0. \n Please enter again.");
takeStone = in.nextInt();
}
removeStones(takeStone); //remove the stone
if (stoneBalance > 0) {
//show the remaining stones
System.out.print(stoneBalance + " stones left:");
printStar(stoneBalance);
} else if (stoneBalance <= 0) {
System.out.println("Game Over\n" + player2 + " wins!\n");
earnPoint(player2);
break;
}
// player2's turn and remove the stones; decision of winning
System.out.println(player2 + "'s turn - remove how many?\n");
takeStone = in.nextInt();
while (takeStone > upperBound || takeStone <= 0) {
System.out.println(
"Invalid, you need to remove stones under upper " +
"bound limit or above 0. \n Please enter again.");
takeStone = in.nextInt();
}
removeStones(takeStone);
if (stoneBalance > 0) {
System.out.print(stoneBalance + " stones left:");
printStar(stoneBalance);
} else if (stoneBalance <= 0) {
System.out.println("Game Over\n" + player1 + " wins!\n");
earnPoint(player1);
break;
}
}
// ask players to play again
//in.nextLine();
System.out.println("Do you want to play again (Y/N):");
playOrNot = in.nextLine();
gamePlayed(player1);
gamePlayed(player2);
} while (playOrNot.equals("Y"));
}
}
您的代码中需要解决以下问题:
- 由于您正在使用
createPlayer
创建一个NimPlayer
,请创建以下构造函数private
并 创建一个私有的无参数构造函数 所以除了使用createPlayer
来创建NimPlayer
. 别无他法
改为:
private NimPlayer(String userName, String surName, String givenName) {
this.userName = userName;
this.familyName = surName;
this.givenName = givenName;
}
- 从
createPlayer
中删除参数int gamePlayed
和int score
,因为当您创建NimPlayer
时,播放器没有gamePlayed
的任何数据和score
。这些东西会在游戏过程中设置。
改为:
public static void createPlayer(String userName, String familyName, String givenName) {
if (id<10) {
playerList[id++] = new NimPlayer(userName, familyName, givenName);
} else {
System.out.println("Cannot add more players.");
}
}
- 由于
score
和gamePlayed
属于个人玩家,即每个个人玩家将拥有 his/herscore
和gamePlayed
独立于其他玩家,这些属性需要是非静态的。只有当变量的值对于所有实例都应该相同时,才应该创建一个static
变量,例如NimPlayer[] playerList
或id
。请注意,我之前曾要求您使用名称counter
而不是id
,因为它应该是编号的计数器。球员的名字,id
令人困惑。如果您想为个别玩家创建一个id
字段,请使用 IDE 的Replace All
功能将所有出现的id
替换为counter
,所有出现Id
与Counter
(用于替换 getter 和 setter),然后在 [=15= 中创建一个非静态private int id;
,如firstName
、familyName
等].
声明 score
和 gamePlayed
如下:
private int score;
private int gamePlayed;
//public getters and setters of score and gamePlayed
score
和gamePlayed
应该按照访问名称的方式访问
if (commandin.equals("displayplayer")) {
String user = in.nextLine().trim();
NimPlayer [] players = NimPlayer.getPlayer();
for (int i = 0; i < NimPlayer.getId(); i++) {
String userCheck = players[i].getUserName().trim();
String userName = players[i].getUserName();
String familyName = players[i].getFamilyName();
String givenName = players[i].getGivenName();
int score = players[i].getScore();
int gamePlayed = players[i].getGamePlayed();
if (user != null && userCheck.equals(user)) {
System.out.println(userName + "," + familyName + "," + givenName + "," + gamePlayed + " games,"
+ score + " wins");
}
}
}
score
的值应该设为
public static int earnPoint(String player) {
int i = 0;
for (i = 0; i < NimPlayer.getCounter(); i++) {
String playerCheck = NimPlayer.getPlayer()[i].getUserName();
if (playerCheck.equals(player)) {
NimPlayer.getPlayer()[i].setScore(NimPlayer.getPlayer()[i].getScore() + 1);
break;
}
}
return NimPlayer.getPlayer()[i].getScore();
}
我完全修改了您的模型代码,这使得其余代码更加简单。创建良好的应用程序模型会使创建应用程序的其余部分变得更加容易。
这是您修改后的 NimPlayer
class。构成这个class的字段都与游戏玩家有关
class 仅由 getter 和 setter 组成。两个设置器添加而不是替换。 class.
中没有静态字段public class NimPlayer {
private final int id;
private final String userName;
private String familyName;
private String givenName;
private int gamesPlayed;
private int gamesWon;
public NimPlayer(int id, String userName, String familyName,
String givenName) {
this.id = id;
this.userName = userName;
this.familyName = familyName;
this.givenName = givenName;
this.gamesPlayed = 0;
this.gamesWon = 0;
}
public int getId() {
return id;
}
public String getUserName() {
return userName;
}
public String getFamilyName() {
return familyName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
public String getGivenName() {
return givenName;
}
public void setGivenName(String givenName) {
this.givenName = givenName;
}
public int getGamesPlayed() {
return gamesPlayed;
}
public void addGamePlayed() {
this.gamesPlayed++;
}
public int getGamesWon() {
return gamesWon;
}
public void addGamesWon() {
this.gamesWon++;
}
}
我新建了一个class,NimModel
来保存游戏状态。 class 是 playerList
以及与 playerList
关联的所有代码所在的位置。
将 playerList
设为 List
会简化代码,但我将 playerList
保留为数组,以向您展示在数组中添加和删除玩家所涉及的代码。
public class NimModel {
private int numberOfPlayers;
private int limit;
private NimPlayer[] playerList;
public NimModel() {
this.numberOfPlayers = 0;
this.limit = 10;
this.playerList = new NimPlayer[limit];
}
public boolean createPlayer(String userName, String familyName,
String givenName) {
if (numberOfPlayers < limit) {
int id = getFirstPlayerSlot();
if (id >= 0) {
playerList[id] = new NimPlayer(id,
userName, familyName, givenName);
numberOfPlayers++;
}
return true;
} else {
return false;
}
}
private int getFirstPlayerSlot() {
for (int i = 0; i < limit; i++) {
if (playerList == null) {
return i;
}
}
return -1;
}
public NimPlayer getPlayer(int id) {
return playerList[id];
}
public NimPlayer getPlayer(String userName) {
for (int i = 0; i < limit; i++) {
if (playerList[i] != null) {
if (userName.equals(playerList[i].getUserName())) {
return playerList[i];
}
}
}
return null;
}
public NimPlayer removePlayer(String userName) {
for (int i = 0; i < limit; i++) {
NimPlayer player = playerList[i];
if (player != null) {
if (userName.equals(player.getUserName())) {
this.playerList[i] = null;
numberOfPlayers--;
return player;
}
}
}
return null;
}
public int getNumberOfPlayers() {
return numberOfPlayers;
}
}
最后,这是您修改后的 Nimsys
和 NimGame
class。同样,我们删除了所有静态引用。
如果您按照方法的调用顺序编写代码,它会使代码更易于阅读和理解。也就是说,先提要点,再提细节。
import java.util.Scanner;
public class Nimsys {
private NimModel nimModel;
public static void main(String[] args) {
Nimsys nimsys = new Nimsys();
nimsys.processCommands();
}
private void processCommands() {
this.nimModel = new NimModel();
Scanner in = new Scanner(System.in);
while (true) {
System.out.print('$');
String commandin = in.nextLine().trim();
if (commandin.equalsIgnoreCase("addplayer")) {
addPlayer(in);
}
if (commandin.equalsIgnoreCase("removeplayer")) {
removePlayer(in);
}
if (commandin.equalsIgnoreCase("editplayer")) {
editPlayer(in);
}
if (commandin.equalsIgnoreCase("displayplayer")) {
displayPlayer(in);
}
if (commandin.equalsIgnoreCase("startgame")) {
startGame(in);
}
}
}
private void addPlayer(Scanner in) {
String inName = in.nextLine().trim();
String[] name = splitName(inName);
if (name != null && name.length == 3) {
NimPlayer player = nimModel.getPlayer(name[0]);
if (player == null) {
nimModel.createPlayer(name[0], name[1], name[2]);
System.out.println("The player has been created.");
} else {
System.out.println("The player is already in "
+ "the list.");
}
} else {
System.out.println("Not Valid! Please enter again!");
}
}
private String[] splitName(String inName) {
String[] splittedLine = inName.split(",");
String[] name = null;
if (splittedLine.length == 3) {
String userName = splittedLine[0].trim();
String familyName = splittedLine[1].trim();
String givenName = splittedLine[2].trim();
name = new String[3];
name[0] = userName;
name[1] = familyName;
name[2] = givenName;
}
return name;
}
private void removePlayer(Scanner in) {
String removeUserName = in.nextLine().trim();
NimPlayer player = nimModel.removePlayer(removeUserName);
if (player == null) {
System.out.println("The player does not exist");
} else {
System.out.println("Player " + player.getUserName() +
" removed successfully!");
}
}
private void editPlayer(Scanner in) {
String inName = in.nextLine().trim();
String[] splittedLine = inName.split(",");
if (splittedLine != null && splittedLine.length == 3) {
String userName = splittedLine[0].trim();
String familyName = splittedLine[1].trim();
String givenName = splittedLine[2].trim();
NimPlayer player = nimModel.getPlayer(userName);
if (player == null) {
System.out.println("The player does "
+ "not exist.");
} else {
player.setFamilyName(familyName);
player.setGivenName(givenName);
System.out.println("Edited successfully");
}
} else {
System.out.println("Invalid user name! Please "
+ "enter again.");
}
}
private void displayPlayer(Scanner in) {
String userName = in.nextLine().trim();
NimPlayer player = nimModel.getPlayer(userName);
String familyName = player.getFamilyName();
String givenName = player.getGivenName();
int gamesWon = player.getGamesWon();
int gamesPlayed = player.getGamesPlayed();
System.out.println(userName + "," + familyName +
"," + givenName + "," + gamesPlayed +
" games," + gamesWon + " wins");
}
private void startGame(Scanner in) {
NimPlayer player1 = null, player2 = null;
do {
String dataIn = in.nextLine().trim();
String[] data = splitData(dataIn);
if (data != null && data.length == 4) {
player1 = nimModel.getPlayer(data[2]);
player2 = nimModel.getPlayer(data[3]);
NimGame game = new NimGame(nimModel, data[0],
data[1], player1, player2);
game.playGame();
}
} while (player1 == null || player2 == null);
}
private String[] splitData(String dataIn) {
String[] splittedLine = dataIn.split(",");
String[] data = null;
if (splittedLine.length == 4) {
String initialStone = splittedLine[0];
String stoneRemoval = splittedLine[1];
String player1 = splittedLine[2].trim();
String player2 = splittedLine[3].trim();
data = new String[4];
data[0] = initialStone;
data[1] = stoneRemoval;
data[2] = player1;
data[3] = player2;
}
return data;
}
}
NimGame class
import java.util.Scanner;
public class NimGame {
NimPlayer player1;
NimPlayer player2;
String playOrNot;
String initialStoneInput;
String dataRemoval;
int stars;
int stoneBalance;
int initialStone;
int upperBound;
public NimGame(NimModel nimModel, String initialStoneInput,
String dataRemoval,
NimPlayer player1, NimPlayer player2) {
this.initialStoneInput = initialStoneInput;
this.dataRemoval = dataRemoval;
this.player1 = player1;
this.player2 = player2;
}
Scanner in = new Scanner(System.in);
public void playGame() {
// Convert user input string into integer
int initialStoneInt = Integer.parseInt(initialStoneInput);
initializeStone(initialStoneInt);
int upperBound = Integer.parseInt(dataRemoval);
System.out.println("Initial stone count: " +
initialStoneInt);
System.out.println("Maximum stone removal: " +
dataRemoval);
System.out.println("Player 1: " + player1.getUserName());
System.out.println("Player 2: " + player2.getUserName());
do {
// while stoneBalance > 0, two players
// keep playing the game
while (stoneBalance > 0) {
// player1's turn and remove the stones;
// decision of winning
System.out.println(player1.getUserName() + "'s "
+ "turn - remove how many?\n");
int takeStone = in.nextInt();
while (takeStone > upperBound ||
takeStone <= 0) {
System.out.println("Invalid, you need "
+ "to remove stones under upper "
+ "bound limit or above 0. \n"
+ "Please enter again.");
takeStone = in.nextInt();
}
removeStones(takeStone); // remove the stone
if (stoneBalance > 0) {
// show the remaining stones
System.out.print(stoneBalance +
" stones left:");
printStar(stoneBalance);
} else if (stoneBalance <= 0) {
System.out.println("Game Over\n" +
player2.getUserName() + " wins!\n");
earnPoint(player2);
break;
}
// player2's turn and remove the stones;
// decision of winning
System.out.println(player2.getUserName() + "'s "
+ "turn - remove how many?\n");
takeStone = in.nextInt();
while (takeStone > upperBound ||
takeStone <= 0) {
System.out.println("Invalid, you need "
+ "to remove stones under upper "
+ "bound limit or above 0. \n"
+ "Please enter again.");
takeStone = in.nextInt();
}
removeStones(takeStone);
if (stoneBalance > 0) {
System.out.print(stoneBalance + " "
+ "stones left:");
printStar(stoneBalance);
} else if (stoneBalance <= 0) {
System.out.println("Game Over\n" +
player1.getUserName() + " wins!\n");
earnPoint(player1);
break;
}
}
player1.addGamePlayed();
player2.addGamePlayed();;
// ask players to play again
// in.nextLine();
System.out.println("Do you want to play "
+ "again (Y/N):");
playOrNot = in.nextLine().trim();
} while (playOrNot.equalsIgnoreCase("Y"));
}
public int initializeStone(int startStones) {
stoneBalance = startStones;
return stoneBalance;
}
public void removeStones(int stonesTaken) {
int updatedBalance = stoneBalance - stonesTaken;
stoneBalance = updatedBalance;
}
private void printStar(int star) {
stars = star;
stars = stoneBalance;
for (int stars = 1; stars <= star; stars++) {
System.out.print(" *");
}
System.out.println();
}
private int earnPoint(NimPlayer player) {
player.addGamesWon();
return player.getGamesWon();
}
}