Edit Specific Instance of Object - java

Say i let players create teams and creating a team calls a new instance of the team class which has an array list called members.
Now in the main class how would i add a player to a team after being invited? i have an addPlayer method in the team class that simply add them to the arraylist but what if there are currently multiple instances of the teams class(other players have created teams) how would it know which one to join?
I do have a variable in the Teams class for the teamLeader which gets set when creating the instance if that could help me edit a certain instance.
Team team = new Team(this, leader);
Any help is appreiciated

You need an identifier to uniquely distinguish each team and you can use that identifier to store the teams in a Map. Something like this:
Map<String,Team> teamMap = new HashMap<String,Team>();
Chose the key type as per your requirement, I chose String for an example

As per your design, You need to keep all teams in a list after creation.
ArrayList teamsList=new ArrayList ();
Team team = new Team(this, leader);
teamsList.add(team);
Then Loop through all teams in addPlayer method and then compare leader and then add a player to it. Something like this -
public void addPlayer (Player player,String leader){
for(int i=0; i<teamListSize;i++)
Team tempTeam=teamsList.get(i);
if(tempTeam.getLeader().equalsIgnoreCase(leader)){
tempTeam.add(player);
break;
}
}

Related

Checking if an ArrayList exists in a map

My football team has 5 different teams and I am trying to make a program to keep a track of which players are registered with each team. I want to be able to add a new player but first the program checks if that player is already registered. I would also be able to add new teams in the future and again I would like to check if that team already exists.
I have made a Map variable with
private Map<String, List<Player>> teamName;
then initialised this in the constructor
teamName = new HashMap<>();
I then have a method to add new teams and new players, I want the method to check if the Club name already exists and then if it does exist, add the player name to that Club. if it doesn't exist then I want the program to add a new Club and then add that player to that club.
So far I have a method for adding a new player,
public void newPlayer(String club, Player name) {
}
I am not sure how I now go about checking that an ArrayList exists for club and if it does add name to this list, if club does not exist then I want to make a new list and add name to it.
if I then run the program and write,
Player jamesAtkinson = new Player();
newPlayer("first team", jamesAtkinson);
it would check if there is a List in the Map called 'first team' and then either add James Atikinson to it, or create a new List called first team and then add James Atkinson.
Is this even possible to do?
Although there are a few problems with code you've provided in the question. What you're looking for is the .containsKey function that hangs off of the Map interface.
if (players.containsKey("first team") {
// Do something
} else {
List<Player> firstTeam = new ArrayList<>();
firstTeam.add(jamesAtikson);
players.put("first team", jamesAtikson);
}

Java - Fancy Two Dimesional Arrays

I am creating a video game were the player can enter and exit rooms. They may also enter rooms within room or sub-rooms. After all of the collision for this I come up with five Rectangle variables/arrays.
static Rectangle exitDoor[] = new Rectangle[1];
static Rectangle subExitDoor[] = new Rectangle[1];
static Rectangle roomDoor[] = new Rectangle[1];
static Rectangle roomLadder[] = new Rectangle[1];
static Rectangle roomInnerLadder[] = new Rectangle[1];
Each room can have multiple of each within. I would like to put all of these arrays within an array that creates two versions of them. What I mean is that if the final two dimesional array is named "room" than room[0][0] and room[1][0] (The second zero being the exitDoor array) would be two different values.
I have tried doing the below, but all it does is do the same thing as the first set of code.
Rectangle[][] roomCat = new Rectangle[][] { exitDoor, subExitDoor, roomDoor, roomLadder, roomInnerLadder };
I am not looking for someone to tell me how to make two dimensional arrays, I can al ready do that. I need someone to tell me how to take them to the next step.
Thanks,
Oak
Well, I didn't understand what you are trying to do with two dimensional arrays. Actually there is nothing special about two dimensional arrays, they are just array of arrays, if you know what I mean.
However if we look back what are you trying to do in the first place. It's not actually very complicated task.
Actually what you're trying to do is a very interesting concept in many areas such as mathematics and art, which is called self-referencing. You can see self-referencing in the paintings of Escher and in the conans of Bach. Take a look at the class below.
class Room {
Room outerRoom;
Room innerRoom;
Room(Room outerRoom, Room innerRoom) {
this.outerRoom = outerRoom;
this.innerRoom = innerRoom;
}
// goes to outerRoom
Room exit() {
return outerRoom;
}
// goes to innerRoom
Room enter() {
return innerRoom;
}
}
It's an implementation of a room in your game. As you mentioned there might be another room inside the room, therefore there might be another room outside the room. So if we want exit the room we go to outerRoom. What handy about this implementation is the outerRoom is a Room too. Therefore it contains inner and outer rooms as well.
You may think this class as a matryoshka doll however what we actually implemented is a basic linked list. You can look it up on the internet, and you can use it while you're making your game however it seems like you're looking for something more.
You want to have many rooms inside a room. What you're looking for is a tree, my friend. Look at the class below:
class Room {
Room outerRoom;
Room[] innerRooms;
// creates a room with n inner rooms
Room (Room outerRoom, int n) {
this.outerRoom = outerRoom;
this.innerRooms = new Room[0];
}
// sets nth room to innerRoom
void addRoom(int n, Room innerRoom) {
innerRooms[n] = innerRoom;
}
// goes to nth room
Room getRoom(int n) {
return innerRooms[n];
}
}
It's another implementation of a room in your game. Instead of having an inner room, we have an array of inner rooms this time. So you can have as many rooms as you want in the room however you can only have one room outside, just like a node of a tree.
So, I recommend you to look up linked lists and trees on the internet to understand the concept of this kind of self-referencing structures.
Also notice that if there isn't any room outside you can make it null, and if you don't want to have any inner rooms you can set the number of inner rooms to 0.
I hope it helps :).

Update ArrayList of Specific Instance

This has been confusing me for a while, picture this
public class someObject {
private ArrayList<Player> listOfPlayers = new ArrayList<Player>();
private String name;
public void addPlayer(Player player){
listOfPlayers.add(player);
}
}
Multiple instances of this object can be created during the game, what i don't understand is how do you update the ArrayList of a specific instance, for example
There are 10 instances currently of the someObject class Player 1, 2 and so on. Player 5 wants to add a player to his listOfPlayers, how would i handle getting the arraylist of his specific instance where he is currently in the listOfPlayers.
What i have been doing is
for (int i = 0; i < objects.size(); i ++){ //ArrayList<someObject>
someObject temp = someObject.get(i);
if (temp.listOfPlayers.contains(player)){
return true;
}
}
Which works but it seems so wrong using for loops in every getter and setter of the someObjects class, is there a better way than this ?
A better solution/alternative would be using a Map.
Map<someObject, List<Players>> objPlayersMap= new HashMap.....
Later, you can check your condition just like
objPlaersMap.get(someObject).contains(...
If you want, u can modify your "Player" class and add an id. With setter and getter u can handle these with this id. Its an idea, if u wanna prefer it more.
The best way is to use a map with the name of the player as a key. In that way you can get the list easily without a loop
Map<String, List<Players>> players = new HashMap<String,List<Players>>();
players.put("player1", new SomeObject());
players.put("player2", new SomeObject());
....
after that you do that:
List<Players> player1 = players.get("player1");

Keeping track of scores in Java

I'm new to Java and I'm currently writing a program for an assignment that represents a 'sports league' (classes to represent player/club/match/league)
My main problems are occurring in the league class. Here are the relevant variables to give you an idea how I'm storing things:
public class League
{
private String leagueName;
private ArrayList<Club> clubs;
private ArrayList<Match> fixtures;
private ArrayList<String> results2;
private TreeMap<Match, String> results;
private String topTeam;
private String goldenBoot;
}
Currently trying to write a method in the League class which will print a 'league table' - i.e. a list of Clubs sorted by their points tally (held as variable in Club class) and I'm drawing a blank on it.
Further to this, I need to write two methods to find the top scorer (golden boot) and find the top team in the league; again I am drawing a blank. Perhaps I am overcomplicating things?
Would be very grateful for suggestions/sample methods
EDIT:
Ok, so that method I'm trying to write is something beginning with:
public void getLeagueTable() {
for(Club c : clubs) {
c.getTally();
}
}
which would give the tally value for each Club object - but how to sort these results, and how to associate the highest with one Club is what's really troubling.
To print the league table, you are going to need to sort the club array and then loop through each item and print the club name.
To sort the club array try using Collections.sort http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Collections.html
.. that is assuming you havent been told to implement your own algorithm
Again, more sorting required to get the top team and top scorer, then you will need to pick the top item from the sorted list.
Hope that helps...
You better use Set rather than ArrayList. And here is a good start for your question :
void printLeagueTable(){
i = 0 ;
while( i != clubs.size() ){
Club club = clubs.get(i);
System.out.println("club: "+i+ "points: " club.points() );
}
}

Reading text file with multiple columns with logic

I'm reading a text file that has multiple columns and I'm storing the information in an array
File looks like this
Player | Team
---------| ---------
PlayerA | Team1
PlayerA | Team2
PlayerB | Team3
PlayerC | Team4
PlayerC | Team5
As you see each player has multiple teams. I am trying to read this file line by line so that at the end of the file I have a List with three players (A, B, and C) and each having their corresponding teams.
Classes:
Player - with Name and List<Team> (getter setter for both)
Team - with Name (getter and setter)
I can't figure out the logic of when to create the Player and Team classes and keep account for when the player name has changed
You can encapsulate your person and team inside two classes Person and Team..
Then, You can use a Map<Person, List<Team>> to maintain various teams for each Person..
Map<Person, List<Team>> mapping = new HashMap<>();
// Read each line from file..
// Get Person and Team object..
// Assuming that you have your `Person` object in person and `Team` object in team
// You need a Comparator for `Person` class to check for `containment`..
if (mapping.contains(person)) {
// Person already exist.. Update the list of Team he has
mapping.get(person).add(team);
} else {
// New entry.. create a new list.. and add it to map..
List<Team> teamList = new ArrayList<>();
teamList.add(team);
mapping.put(person, teamList);
}
NOTE : - You need to have a Comparator for your Person class to be compared..
I think I have given you a base to work upon.. Rest you need to workaround.. How to populate your object.. How to implement Comparator.. and all that..
Typically I would not question the validity of the model proposed but ... does not make more sense that the teams are those that have many players rather than the opposite?
Anyhow, assuming that the player name cannot be changed by a team appearing again with a different player name:
BufferedReader input = ...;
Map<String,Player> playersByName = new HashMap<String,Player>();
String line;
while ((line = input.readLine()) != null) {
String playerName;
String teamName;
// code to parse the player and team names from 'line' comes here.
Player player = playersByName.get(playerName);
if (player == null)
playersByName.put(playerName,player = new Player(playerName));
Team team = new Team(teamName);
if (!player.getTeams().contains(team))
player.getTeams().add(team);
}
The code assumes that the Player constructor creates an empty list of teams.
Although the above will work using a list to hold the teams for a player I would suggest that you use a Set instead for efficiency if the number of teams that player has can be quite big. In that case you do not need the last conditional, you could add directly.
Even better if you hide the List or Set implementation entirely and you add operations to manipulate the team list safely within the Player class.
Remeber that if you use a (hashed) Set solution (hidden or exposed) you'll need to override the equals and hashCode functions appropriately in the Team class (delegating them on its name would work very well).

Categories