如何在三个类之间使用setter和getter传递值 [英] How to pass values using setter and getter among three classes

查看:84
本文介绍了如何在三个类之间使用setter和getter传递值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在练习一个经典的Nim游戏项目.我现在实现的是:

I've been practicing a project which is the classical Nim game. What I've achieved now is:

  1. 添加,删除,编辑,显示播放器. (Nimsys和NimPlayer)
  2. 选择两个玩家玩游戏. (NimGame类)

每次游戏结束时,我需要将这两个东西从NimGame返回到NimPlayer.然后我可以在Nimsys中使用getter:

Every time when the game ends, I need to return these two things from NimGame to NimPlayer. Then I can use getter in Nimsys:

  1. 如果玩家获胜,他/她的得分+1.
  2. 每场比赛后,每次比赛的球员的比赛次数均为+1.

我已经尝试过的是将NimPlayer中的得分"和"gamePlayed"传递给NimGame,将首先为0的getter放入设置器中以设置数字+1.

What I've already tried was to pass the "score" and "gamePlayed" from NimPlayer to NimGame, putting the getter, which is 0 at first, in the setter to set the number +1.

scores = NimPlayer.setScore(NimPlayer.getScore() + 1);

但是,我不知道如何将此处的分数"传回给NimPlayer使用.我希望将分数传递回NimPlayer.然后,我可以从Nimsys调用它.这是我的代码.

However, I don't know how to pass the "scores" here back to NimPlayer to be used. I am hoping to pass the scores back to NimPlayer. Then, I can call it from Nimsys. Here is my code.

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命令调用这些值时遇到问题.应该是这样的:

The above is my main method Nimsys. I have a problem calling these values using the displayplayer command. It should be like this:

userName,familyName,givenName,gamePlayed "games",score "wins"

下面是我的NimPlayer类:

Below is my 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部分:

And finally the NimGame part:

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

}
}

推荐答案

以下问题需要在您的代码中解决:

The following things need to be addressed in your code:

  1. 由于要使用createPlayer创建NimPlayer,因此使以下构造函数private创建私有的无参数构造函数,以便除了使用创建NimPlayer.
  1. Since you are creating a NimPlayer using createPlayer, make the following constructor private and also create a private no-arg constructor so that there is no other way than using createPlayer to create a NimPlayer.

将其更改为:

private NimPlayer(String userName, String surName, String givenName) {
    this.userName = userName;
    this.familyName = surName;
    this.givenName = givenName;
}

  1. createPlayer中删除参数int gamePlayedint score,因为在创建NimPlayer时,播放器没有用于gamePlayedscore的任何数据.这些东西将在游戏过程中设置.
  1. Remove the parameters, int gamePlayed and int score from createPlayer because when you create a NimPlayer, the player does not have any data for gamePlayed and score. These things will be set during the course of game.

将其更改为:

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

  1. 由于scoregamePlayed属于各个玩家,即每个玩家的scoregamePlayed都将独立于其他玩家,因此这些属性必须是非静态的.仅当假定所有实例的变量值都相同时,才应创建static变量. NimPlayer[] playerListid.请注意,我之前曾要求您使用名称counter代替id,因为它应该是否号的计数器.玩家,因此名称id令人困惑.如果要为单个玩家创建id字段,请使用IDE的Replace All功能将id的所有出现替换为counter,将Id的所有出现替换为Counter(用于替换吸气剂和设置器),然后在NimPlayer内创建一个非静态的private int id;,如firstNamefamilyName等.
  1. Since score and gamePlayed belong to individual players i.e. each individual player will have his/her score and gamePlayed independent from those of other players, these attributes need to be non-static. You should create a static variable only when the value of the variable is supposed to be same for all instances e.g. NimPlayer[] playerList or id. Note that I had asked you earlier to use the name, counter instead of id because it is supposed to be a counter for the no. of players and therefore the name, id is confusing. If you want to create an id field for individual players, use the Replace All feature of your IDE to replace all occurances of id with counter, all occurances of Id with Counter (for replacing getters and setters) and then create a non-static private int id; like firstName, familyName etc. inside NimPlayer.

声明scoregamePlayed如下:

private int score;
private int gamePlayed;
//public getters and setters of score and gamePlayed

    应该使用访问名称的方式访问
  1. scoregamePlayed
  1. score and gamePlayed should be accessed the way you are accessing names

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

  1. score的值应设置为
  1. The value of score should be set as

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

这篇关于如何在三个类之间使用setter和getter传递值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆