javagettersettermutators

How to pass values using setter and getter among three classes


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

  1. Add, remove, edit, display, players. (Nimsys and NimPlayer)
  2. Selecting two players to play a game. (NimGame class)

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. If the player wins, his/her score +1.
  2. Every time after a game, the number of game +1 for the player who played.

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

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

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"

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

}

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

}
}

Solution

  • The following things need to be addressed in your code:

    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.

    Change it to:

    private NimPlayer(String userName, String surName, String givenName) {
        this.userName = userName;
        this.familyName = surName;
        this.givenName = givenName;
    }
    
    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.

    Change it to:

    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. 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.

    Declare score and gamePlayed as follows:

    private int score;
    private int gamePlayed;
    //public getters and setters of score and gamePlayed
    
    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. 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();
    }