I recently changed my Locale constructor to take in an array called Item instead of just an item name and now I'm having some difficulties with taking an item in my game. This is a text adventure game where the player can move around the map and pick up items that are in the rooms. I am getting the error: "The method add(String) in the type ArrayList is not applicable for the arguments (Item)". I'm not sure how to fix this issue.
Thank you for all help!
Here is my code:
static int currentLocation = player1.currentRoom;
//Items {itemName, itemDes}
static Item[] items = {
new Item ("map","A layout of your house."),
new Item ("battery", "A double A battery."),
new Item ("flashlight", "A small silver flashlight."),
new Item ("key", "This unlocks some door in your house."),
};
//Locations {roomName, description, Item}
static Locale[] locales = {
new Locale("bedroom","You see the outline of a bed with your childhood stuffed bear on it.",items[0]),
new Locale("hallway","A carpeted floor and long pictured walls lie ahead of you.",null),
new Locale("kitchen","The shining surface of your stove reflects the pale moonlight coming in the window over the sink.",items[1]),
new Locale("bathroom","You find yourself standing in front of a mirror, looking back at yourself.",items[2]),
new Locale("living room","You stub your toe on the sofa in the room, almost falling right into the TV.",null),
new Locale("dining room","You bump the china cabinet which holds your expensive dishes and silverware.",items[3]),
new Locale("office","The blinking light from the monitor on your desk can be seen in the dark",null),
new Locale("library","The smell of old books surrounds you.",null),
new Locale("basement","You reach the top of some stairs and upon descending down, you find the large metal generator.",null),
};
//Take
else if(response.equalsIgnoreCase("T")){
Locale locale = locales[currentLocation];
// check if the locale has an item.
if(locale.item != null){
// create an "ArrayList" with all the items from the players inventory or an empty one if the inventory is "null"
ArrayList<String> inventory;
if(player1.inventory != null){
inventory = new ArrayList<String>(Arrays.asList(player1.inventory));
}
else{
inventory = new ArrayList();
}
// add the item to the list and set the list as the player's inventory by converting it to an array.
inventory.add(locale.item);
player1.inventory = inventory.toArray(new String[inventory.size()]);
System.out.println("\tA " + locale.item + " was added to the inventory");
System.out.println("\n\tYou can view your inventory by pressing 'I'.");
System.out.println("\n\tFive points have also been added to your score.");
player1.score += 5;
System.out.println("\n\tThis is your current score: "+player1.score);
locale.item = null;
}
// this locale doesn't have an item.
else{
System.out.println("\tThere is no item to pick up");
}
break;
}//End of Take
This is my Locale class:
public class Locale {
//Locale must have name, description, and Item
public static int roomNumber;
public String roomName;
public String description;
public Item item;
public Locale(String roomName, String description, Item item){
this.roomName = roomName;
this.description = description;
this.item = Item;
}
}
This is my Item class:
public class Item {
//item must have a name and a description (both strings)
public String itemName;
public String itemDes;
public Item (String itemName, String itemDes){
this.itemName = itemName;
this.itemDes = itemDes;
}
}
item[i] references an Item object. If Item is a parameter for your Locale constructor i don't see why this wouldn't work. Are there any specific error messages?
Related
I am trying to make an erase function to delete the teams of the tournament using the team code (value c in the constructor). Firstly I want to check if that team exists in the objects I made in the main method. Is that possible to do that using an if statement?
Exercise:
Create a java application that stores data for various football teams. Each team has a name, a code and the current points in the championship. In your class create methods for registering new teams, erasing existing teams using their code and showing a list for all the teams currently active in the championship
package assignment.exercise4;
public class Data {
private String name = "";
private int code = 0;
private static int register;
private int erase;
private int currentpoints = 0;
public Data(int c, int points, String n) { //constructor
code = c;
this.currentpoints = points;
name = n;
}
public void Erase(int c)
{
code = c;
if(code != 0)
System.out.println("Team with Code: "+code+" has been erased" );
else
System.out.print("Team with code "+code+" does not exist!");
}
public void Register(String newTeam,int code)
{
name = newTeam;
this.code = code;
System.out.println("New Team " + name + " registered with code " + code);
}
public void print()
{
System.out.println("Team name: " + name + "\nTeam code: " + code + "\nTeam points: " + currentpoints + "\n");
}
}
/*
public static void main(String[] args) {
System.out.println("\nList of Teams: \n");
Data t1 = new Data(110,42,"Juventus");
Data t2= new Data(105,45,"Manchester City");
Data t3= new Data(240,50,"Barcelona");
Data t4= new Data(122,36,"Arsenal");
Data Team = new Data(0,0,""); //use for erase
t1.print();
t2.print();
t3.print();
t4.print();
System.out.println("Teams erased: \n");
Team.Erase(110);
Team.Erase(122);
Team.Erase(0);
System.out.println("\n\nTeams Registered: \n");
t1.Register("Real madrid", 11);
t1.Register("Atletico Madric", 112);
}
}
*/
What are you trying to erase the teams from?
If they were in a list, for example...
Data t1 = new Data(110,42,"Juventus");
Data t2= new Data(105,45,"Manchester City");
Data t3= new Data(240,50,"Barcelona");
Data t4= new Data(122,36,"Arsenal");
List<Data> teams = Arrays.asList(t1, t2, t3, t4);
...you could create a list with a team erased like this...
public List<Data> erase(List<Data> team, int id) {
return team.stream()
.filter(t -> t.getId() != id)
.collect(Collectors.toList());
}
So...
List<Data> remainingTeam = erase(team, 122); // Removes Arsenal
...would remove the first element from the list
I will not answer this to elaborately since it is homework. I will try to give you a hint though.
If you have a team and want to do something with it. Otherwise you just have a team which just stays there in a particular scope (if you do not know what scope is, look it up!). If you have a team you most likely want do do something with it. In this case you seem to want to store information about the teams to use in a championship. Important to note here is that the teams are not the focus here. The real focus is the Championship. The teams are just a part of the championship. There can still be a championship even if all teams does not choose to participate. But you want all teams choosing to participate to be registered to this particular championship (eg UEFA Champions League).
This leads to something called aggregate or association depending on how hard you want to tie the object to the championship. However you do probably not need to pursue these terms any further at this point. What is important to remember is that there is an "has a" relation between the championship and the teams. The championship "has a" collection of participating teams. This is normally reflected in this way in code,
public class Championship {
private Team[] teams; // Or List<Team>, Collection<Team>, HashMap<Team>, ...
}
The Championship can then have methods for registering a team, removing a team, updating status, etc...
public void register(Team t) {
if (numberOfTeams < teams.length) {
teams[numberOfTeams] = t; // Index starts at zero
numberOfTeams++;
} else {
throw new IndexOutOfBoundsException("The list is full. " +
"No more teams may be registered!")
}
}
Even though the function erasing a team was requested, I believe I will not write it down. This design is so different from your original intent, so that writing the erase function will likely solve your complete homework. However, you do actually not have to erase the team it is perfectly possible to just overwrite the position with the next team as,
teams[i] = teams[i+1];
Hope this helps!
Short answer:
public void erase(int id) {
// who needs an if statement, if we can use predicates?
teams.removeIf(team -> team.getId() == id);
}
But this will not work with your current code. Your current code misses the container for your teams.
Longer answer:
For the fun of it. Solving your homework:
class Team {
int id;
String name;
int points;
Team(int id, String name, int points) {
this.id = id;
this.name = name;
this.points = points;
}
#Override
public String toString() {
// ugly formatted... another homework? ;-)
return "Team '" + name + "' (" + id + "): " + points;
}
}
Note, that I will not add any getter or setter, nor will I care about visibility here. I will leave that as another homework for you.
class Championship {
List<Team> teams = new ArrayList<>();
void register(Team team) {
teams.add(team);
}
void erase(int id) {
teams.removeIf(team -> team.id == id);
}
#Override
public String toString() {
// for additional fun... sorted by descending points
return "=== Championship table ===\n"
+ teams.stream()
.sorted((o1, o2) -> Integer.compare(o2.points, o1.points))
.map(Objects::toString)
.collect(Collectors.joining("\n"));
}
}
Somewhere else:
public static void main(String[] args) {
Championship championship = new Championship();
championship.register(new Team(1, "not the best ones", 3));
championship.register(new Team(2, "The better ones", 7));
championship.register(new Team(3, "The winners", 11));
System.out.println(championship);
championship.erase(3);
System.out.println(championship);
}
Output:
=== Championship table ===
Team 'The winners' (3): 11
Team 'The better ones' (2): 7
Team 'not the best ones' (1): 3
=== Championship table ===
Team 'The better ones' (2): 7
Team 'not the best ones' (1): 3
Too much of information? Just start with something like a championship-class or at least use a collection of Teams (e.g. List<Team>).
By the way... Do not deliver this solution as your homework, except you understand what is going on and you can explain it with your own words. Otherwise you are only betraying yourself.
Sorry if this is an easy answer or has been answered, but have searched and couldnt find anything. I am currently creating a supermarket checkout line with the products in a DefaultListModel, each product having a name, price, weight and code as shown below
public class Product {
private String name;
private double weight;
private double price;
private int code;
public Product (){
}
public Product (String Name, double kg, double pounds, int id){
name = Name;
weight = kg;
price = pounds;
code = id;
public String toString (){
return name + " - " + "£" + price + " Product # " + code;
and the products put into a list
public class productList extends DefaultListModel {
public productList (){
super();
}
public void addProduct (String name, double weight, double price, int code){
super.addElement(new Product(name, weight, price, code));
this has been used in the GUI for the checkout in the code segments as follows
private DefaultListModel defaultMainList = new DefaultListModel();
//other code
currentBasket.setModel(defaultMainList); //currentBasket is name of jlist
productsList = new productList();
productsList.addProduct("bananas", 0.5, 0.99, 1);
productsList.addProduct("apples", 0.8, 1.39, 2);
//etc etc, other products emitted
mainCheckoutList.setModel(productsList);
//unimportant code
addBasketItem = new JButton();
getContentPane().add(addBasketItem);
addBasketItem.setText("Add >");
addBasketItem.setBounds(215, 108, 62, 31);
addBasketItem.addActionListener(new ActionListener(){
public void actionPerformed (ActionEvent e){
defaultMainList.addElement(productsList.getElementAt(mainCheckoutList.getSelectedIndex()));
mainTillPrice.setText((defaultMainList.toString()));
this current code adds the item from the jlist on the left (main checkout list, which is my list of available products) to the jlist on the right which is my basket. It also adds the entire string of characters in the right list to the jtextfield called mainTillPrice, i want to know if there is any way just to add the price, eg. for the bananas object add 0.99, and then with subsequent items added add their prices as well to keep a running total. Any help would be appreciated and again sorry for any problems in explanation or code, i am fairly new.
Well, I wouldn't be using defaultMainList.toString(). You will need to get the Product which is been added, get the price of the Product and add it to the current tally. This value would then need to be added to the mainTillPrice text field
public void actionPerformed (ActionEvent e){
Product product = (Product)mainCheckoutList.getSelectedItem();
defaultMainList.addElement(product);
runningTally += product.getPrice();
mainTillPrice.setText(NumberFormat.getCurrencyInstance().format(runningTally));
This will require you to create an instance field called runningTally and assumes you have a method getPrice in your Product
I'm trying to take one parameter from the parent class of Car and add it to my array (carsParked), how can i do this?
Parent Class
public class Car
{
protected String regNo; //Car registration number
protected String owner; //Name of the owner
protected String carColor;
/** Creates a Car object
* #param rNo - registration number
* #param own - name of the owner
**/
public Car (String rNo, String own, String carColour)
{
regNo = rNo;
owner = own;
carColor = carColour;
}
/** #return The car registration number
**/
public String getRegNo()
{
return regNo;
}
/** #return A String representation of the car details
**/
public String getAsString()
{
return "Car: " + regNo + "\nColor: " + carColor;
}
public String getColor()
{
return carColor;
}
}
Child Class
public class Carpark extends Car
{
private String location; // Location of the Car Park
private int capacity; // Capacity of the Car Park - how many cars it can hold
private int carsIn; // Number of cars currently in the Car Park
private String[] carsParked;
/** Constructor for Carparks
* #param loc - the Location of the Carpark
* #param cap - the Capacity of the Carpark
*/
public Carpark (String locations, int room)
{
location = locations;
capacity = room;
}
/** Records entry of a car into the car park */
public void driveIn()
{
carsIn = carsIn + 1;
}
/** Records the departure of a car from the car park */
public void driveOut()
{
carsIn = carsIn - 1;
}
/** Returns a String representation of information about the carpark */
public String getAsString()
{
return location + "\nCapacity: " + capacity +
" Currently parked: " + carsIn +
"\n*************************\n";
}
}
Last Question Method
public String getCarsByColor (String carColour)
{
for (int num = 0; num < carsParked.length; num++)
{
if ( carColour.equals(carsParked[num]) )
{
System.out.print (carsParked[num]);
}
}
return carColour;
}
I have this so far so that if "red" is put in the parameters, it would list all the cars with the color red and it's corresponding information but does not seem to work ~_~.
You seem to have the wrong relationship here: a car park is not a car. I would recommend against using inheritance in either direction between these classes. And Carpark should probably just have an array or collection of cars.
Also note that the parameter carsIn isn't necessary - just get the length of the array of cars (or size() if it's a Collection).
Edit: Okay, ignoring the inheritance part, it seems like it makes sense to add cars when driveIn is called, and remove them when driveOut is called.
driveIn should probably take a Car as an argument, so the method can access the parameter you want to store (personally I would just store Car references, but fine). Since we're going to be adding and removing these parameters, it'll be much easier to use a List that can resize itself instead of an array, like ArrayList. For example:
private final List<String> carsRegNosParked = new ArrayList<String>();
public void driveIn(Car car) {
carsRegNosParked.add(car.getRegNo());
}
It's less clear what driveOut should do. It could take a specific registration number to remove:
public void driveOut(String regNo) {
carsRegNosParked.remove(regNo);
}
Or it could just indiscriminately remove a car, say the first car added:
public void driveOut() {
if (!carsRegNosParked.isEmpty()) {
carsRegNosParked.remove(0);
}
}
Note the difference between remove(Object) and remove(int).
First change carsParked to a list. So:
private String[] carsParked;
becomes
private List<String> carsParked;
Then in you constructor initialize it to an empty list by doing:
carsParked = new ArrayList();
Then in your drive in method, make it take a car parameter and pull the param you want:
public void driveIn(Car car) {
carsParked.add(car.getRegNo());
}
Also you do not need to keep track of the number of cars this way. Since you could always do carsParked.size() to find out.
Now I would probably change that list to be List<Car> instead of string and just dump the whole car in there. Sure you may only need one item right now, but who knows down the road, maybe you will need something else.
EDIT:
Sure you could do it with an simple array. The issue with that is sizing. Say you initially create an array of size 5, when you go to add the 6 item you will need to create a new larger array, copy the original data, then add the new item. Just more work. Now if the idea is you have a carpark, and it can have X number of spots then you initilize your array to that size from the begining.
public Carpark (String locations, int room){
location = locations;
capacity = room;
//this creates an array with the max number of spots
carsParked = new String[capacity];
//also good idea to init
carsIn = 0; //initial number of cars parked
}
then in your driveIn() method:
public void driveIn(Car car) {
carsParked[carsIn] =car.getRegNo();
carsIn=carsIn+1;
}
now driveOut()
public void driveOut(Car car) {
//loop through the array until we find the car
for (int i=0; i < carsParked.length; i=i+1){
if (car.getRegNo().equals(carsParked[i])){
//we found the car, so set the space null
carsParked[i] = null;
carsIn=carsIn-1;
//stop looping now
break;
}
}
}
Looks nice doesn't it. Well no it is not. Now the driveIn will not work, since we have null spots scattered all over the place. How do we fix it:
public void driveIn(Car car) {
//loop through the array until we find a null spot,
//then park the car
for (int i=0; i < carsParked.length; i=i+1){
if (carsParked[i] == null){
//we found the car, so set the space null
carsParked[i] = car.getRegNo();
carsIn=carsIn+1;
//stop looping now
break;
}
}
}
It could still be improved further. I would probably still change String[] carsParked to Car[] carsParked as to not throw away information.
I would also change the driveIn and driveOut methods to return booleans to indicate if the successfully parked or un-parked a car.
Final Edit:
Okay, if you want to keep track of what cars are parked in the car park and which spot they are in you need to know enough about each car to make it unique. In your case you may only need regNo. So when you call driveIn or driveOut you have to pass that information so we can store it at the appropriate index (parking spot) in the array. Otherwise all you will know is a car was parked somewhere, or that a car left. Not which spots are open.
So in short the parameter Car car in those two methods contain the information needed to uniquely identify each car that is being parked, or is leaving. Without it the car park instance would have no clue who is currently parked, or where they are parked.
I am doing this Java assignment for hours and stuck with this tester class for very almost 5 hours.
In this assignment, I have created a Product class, a Money class, a LineItem class and an Inventory class. Now i need to create a test class to test the program by putting new lineitems into the inventory array.
In the tester class, I am trying to create a static method public static void addTestItems(Inventory theInventory) which suppose to add 4 items. For each item I will need to create a product object followed by a LineItem object to contain the newly created product. next i need to use a method from the inventory class to add the items into the array in the inventory class.
What i have tried too so far:
private static void addTestItems(Inventory theInventory)
{
Inventory[] _items;
Product product1 = new Product("Book","Objects first with Java"," An excellent introductory Java textbook");
Product product2 = new Product("CD","The dark side of the moon","The all-time classic Pink Floyd album");
Product product3 = new Product("DVD", "Transformers","Robots in disguise");
Product product4 = new Product("Laptop","Lenovo T42","A good yet affordabble laptop");
Money unitPrice1 = new Money(29,99);
Money unitPrice2 = new Money(4,99);
Money unitPrice3 = new Money(9,99);
Money unitPrice4 = new Money(450,0);
_items[0] = new LineItem(product1,5,unitPrice1);
_items[1] = new LineItem(product2,8,unitPrice2);
_items[2] = new LineItem(product3,200,unitPrice3);
_items[3] = new LineItem(product4,9,unitPrice4);
}
The current error is incompatible types- found LineItem but expected Inventory so i tried changing Inventory[] _items; to LineItem[] _items;. But the error was variable _items may not be initialise.
Sorry guys I am a real noob in Java, I tried searching on-line for ages but I do not quite understand most results. The only one i understand was http://forums.devshed.com/java-help-9/bluej-compiler-error-cannot-find-symbol-variable-object-688573.html but i tired putting into my context but failed. I also found lot of results but they had constructors and instance variables in them which my teacher specifically mentioned that I will not need them.
Wonder if expert could guide me along like let me know my mistakes. Thanks thanks.
The inventory class:
/**
* In the Inventory class, it is merely to create a list / array of product which allows the information from the linitem to be put with an index.
* For example, for the first product, we can use the inventory class to input it into the index 1. and he next product into index 2 and so on.
* It is suse to create an array and inputing the lineitem information into it.
*
* #author (your name)
* #version (a version number or a date)
*/
public class Inventory
{
// instance variables - replace the example below with your own
private LineItem[] _items;
private int _numItems;
/**
* Constructor for objects of class Inventory
*/
public Inventory()
{
// initialise instance variables
_items = new LineItem[1000];
_numItems = 0;
}
/**
* An example of a method - replace this comment with your own
*
* #param y a sample parameter for a method
* #return the sum of x and y
*/
public void addItem(LineItem item)
{
_items[_numItems]= item;
_numItems++;
}
public String toString()
{
String result="";
int i=0;
while (i < _numItems)
{
result = result + _items[i] + "/n";
i++;
}
return result;
}
public void print()
{
String myResult=this.toString();
System.out.println(myResult);
}
public Money getTotalValue()
{
int i=0;
Money total= new Money(0);
while (i<_items.length)
{
total = total.add(Money.NO_MONEY);
i++;
}
return total;
}
public LineItem getItem(String productName)
{
int i = 0;
LineItem itemDetails = null;
while (i<_items.length)
{
if (_items[i].equals(productName))
{
itemDetails= _items[i];
}
else
{
//do nothing
}
i++;
}
return itemDetails;
}
}
I have yet to comment on the methods yet but will do so once i understand it.
Your array is of type Inventory[] - but you're trying to assign references of type LineItem. You're also not initializing it. Change this:
Inventory[] _items;
to this:
LineItem[] _items = new LineItem[5];
And all should be well - although you're not using index 0 (which is why you need it to be size 5) and you're not doing anything with the array afterwards either...
Another alternative to using an array is to use a List:
List<LineItem> items = new ArrayList<LineItem>();
items.add(new LineItem(product1, 5, unitPrice1));
items.add(new LineItem(product2, 8, unitPrice2));
items.add(new LineItem(product3, 200, unitPrice3));
items.add(new LineItem(product4, 9, unitPrice4));
... next think about what you actually want to do with the items variable.
LineItem[] _items = new LineItem[4];
then the index starts from 0 not from 1,
_items[4]
will return indexoutofbounds error
A few things:
incompatible types- found LineItem but expected Inventory
is caused by the fact that your array is supposed to contain Inventory objects but you're assigning LineItems to it instead
variable _items may not be initialise
means that you have your _items object but you haven't initialized it to anything. You want to do
LineItem[] _items = new LineItem[4];
PS: If you want dynamically sized arrays, don't know how many line items you'll potentially load, etc etc use a vector or a collection or something along those lines.
Also,
_items[1] = new LineItem(product1,5,unitPrice1);
_items[2] = new LineItem(product2,8,unitPrice2);
_items[3] = new LineItem(product3,200,unitPrice3);
_items[4] = new LineItem(product4,9,unitPrice4);
In Java, array elements start with index 0 and not 1
_items
is a wonky variable name that makes your team mates sneeze in your coffee
Basically I'm trying to get my head around creating a java program that manages teams and players.
From my understanding I would have a team and a player class. In the team class there would be the get and set methods, as well as some form of collection to store the players in right, such as an array list? Then in the player class the relevant get and set methods.
This setup would be because one team have one to many players right?
I've had no end of trouble trying to get this working. One particular problem I've encountered is that every time I create a team object, and add a player object to it, then create another team object and another player but if I list the players for that new team it shows the previous player added to the first team as well as the new player.
So I figured it was back to the drawing board and wondered if someone could offer some general advice about how they would structure this?
Many thanks,
import java.util.Iterator;
public class test {
public test() {
}
//Method to show the team and its players
public static void showTeamPlayers(Team aTeam) {
Player players;
System.out.println(aTeam.getTeamName());
Iterator e = aTeam.getPlayerList().iterator();
while (e.hasNext()) {
players = (Player)e.next();
System.out.println("\t" + players.getPlayerNumber() + " " + players.getPlayerName());
}
System.out.println("");
}
public static void main(String[] args) {
int teamID;
String teamName = "";
//First create a divison/league
League DivisionOne = new League("Division One");
//Create a new team object
Team team = new Team(teamName);
//Asks the user to enter a team name and stores the input
UserInput.print("Enter team name:");
teamName = UserInput.readString();
team.setTeamName(teamName);
//Add the team
DivisionOne.addTeam(new Team(teamName));
Player player = new Player(0, "Dave");
Player player1 = new Player(1, "Dennis");
Player player2 = new Player(2, "Peter");
//Add to team
team.addPlayer(player);
team.addPlayer(player1);
team.addPlayer(player2);
test.showTeamPlayers(team);
//Asks the user to enter a team name and stores the input
UserInput.print("Enter team name:");
teamName = UserInput.readString();
team.setTeamName(teamName);
//Add the team
DivisionOne.addTeam(new Team(teamName));
Player player3 = new Player(3, "Creamer");
Player player4 = new Player(4, "Matt");
Player player5 = new Player(5, "John");
//Add to team 1
team.addPlayer(player3);
team.addPlayer(player4);
team.addPlayer(player5);
test.showTeamPlayers(team);
}
}
Your structure should be totally right this way (and btw, "one to many associations" are described with "1:n" or "1:(1..n)" ).
Either you have definitely a bug somewhere in your code (post it ;)), for example a static field or used an identifier twice, or you could maybe run into problems with an ArrayList here (try LinkedList for test purposes), but I'm not sure at that.
EDIT:
You forgot to post your model, we're only seeing the test of it, but there you got already a few bugs:
Team team = new Team(teamName);
teamName = UserInput.readString();
team.setTeamName(teamName);
So far, so good. Except that its senseless, to create an instance of Team with an empty teamName and then reset it afterwards, but nvm....
DivisionOne.addTeam(new Team(teamName));
Babam, you're not adding your created Team instance above to DivisionOne, no you're creating a new one. Actually, thats Bug No.1
team.addPlayer(player);
team.addPlayer(player1);
team.addPlayer(player2);
But you're putting the new players to the instance you created above, they're not getting to the team which is created for DivisionOne.... Bug No.2 if you want so...and then
team.setTeamName(teamName);
DivisionOne.addTeam(new Team(teamName));
.
.
.
team.addPlayer(player3);
team.addPlayer(player4);
team.addPlayer(player5);
And again, you're only setting a new teamName of your first instance of Team, and then your're creating a new Team for DivisionOne. So far, Bug No.3 ;)
But you're putting some new players to the "old" team instance, same one as above.
All in all, your created "team" instance has nothing to do with your DivisionOne. So, you created an instance of Team, putting all together six players in it and you call 2 times showTeamPlayers on it. No surprise after all, that the first 3 players are still in there....
Last Point:
League DivisionOne = new League("Division One");
should be
League divisionOne = new League("Division One");
Since a variable never starts with a capital letter, "DivisionOne" could also be a static class (cause classes are always starts with capita letters...)
Well bugs are already mentioned by PaddyG. Here is the soln:
Replace this code:
teamName = UserInput.readString();
team.setTeamName(teamName);
//Add the team
DivisionOne.addTeam(new Team(teamName));
with:
teamName = UserInput.readString();
team = new Team(teamName);
//Add the team
DivisionOne.addTeam(team);
And also replace:
teamName = UserInput.readString();
team.setTeamName(teamName);
//Add the team
DivisionOne.addTeam(new Team(teamName));
Player player3 = new Player(3, "Creamer");
Player player4 = new Player(4, "Matt");
Player player5 = new Player(5, "John");
with:
teamName = UserInput.readString();
team = new Team(teamName);
//Add the team
DivisionOne.addTeam(team);
Player player3 = new Player(3, "Creamer");
Player player4 = new Player(4, "Matt");
Player player5 = new Player(5, "John");
As you can see in the above code that we updated the team variable with the new instance for the new team. And this new instance is added to the DivisionOne. When you are doing DivisionOne.addTeam(new Team(teamName)); you are creating and adding a brand new instance to
DivisionOne but the instance to which you are adding players is a different one (held by the team variable). So the soln is to create a new instance and set the variable team with the this newly created instance and then add players to it and add it to DivisionOne.
I've had no end of trouble trying to get this working. One particular
problem I've encountered is that every time I create a team object,
and add a player object to it, then create another team object and
another player but if I list the players for that new team it shows
the previous player added to the first team as well as the new player.
Make sure the team objects don't share any fields. Maybe you were using a 'static' field for the list that holds the players? If you declare a field static, it will be shared among all team instances, which is probably not what you want.
Seeing your code would be helpful, but given your description, I'd imagine starting with something like this as an example:
// Team.java
public class Team {
private String name;
private List<Player> players;
public Team(String name) {
this.name = name;
this.players = new ArrayList<Player>();
}
public String getName() {
return name;
}
public List<Player> getPlayers() {
return players;
}
}
// Player.java
public class Player {
private String name;
public Player(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
// Main.java
public class Main {
public static void main(String[] args) {
Team team1 = new Team("Team #1");
Team team2 = new Team("Team #2");
team1.getPlayers().add(new Player("Bob"));
team2.getPlayers().add(new Player("Joe"));
}
}
I agree with #Kaleb's answer, but I'll give you an alternative (if you want)...
public class Player {
private String name;
protected int speed;
protected int health;
public Player(String name, int speed, int health) {
this.name = name;
this.speed = speed;
this.health = health;
}
}
public class Main {
public static void main(String[] args) {
Map<Player> team1 = new HashMap<Player>();
Map<Player> team2 = new HashMap<Player>();
System.out.print("Enter the name of the player followed by its speed, health, and team number:");
java.util.Scanner sc = new java.util.Scanner(System.in).useDelimiter(",");
String name = sc.next();
int speed = sc.nextInt();
int health = sc.nextInt();
if (sc.nextInt() == 1) {
team1.put(new Player(name, speed, health));
} else {
team2.put(new Player(name, speed, health));
}
}
}