A java array of objects - java

I have an assignment where I have to create three classes, a client class that performs all I/O, a catalog class that maintains a list of catalogItem objects and a catalogItem class that defines a single item in the store's catalog.
I'm trying to start simple at first and create the array and make sure that it is accepting data before I move on to the rest of the assignment. I was able to compile it with no issues but when I am trying to display the array, I get nothing.
import java.util.Scanner;
public class lab3
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
Catalog catalog = new Catalog();
boolean endCatalog = false;
while (!endCatalog)
{
System.out.println("Please choose and option: \n"
+ "1 - Display all items of the catalog\n"
+ "2 - Display an item by keyword\n"
+ "3 - Add an item to the catalog\n"
+ "4 - Remove an item from the catalog\n"
+ "5 - Change the cost of one item in the catalog\n"
+ "6 - Change the cost of all items in catalog by percent\n"
+ "7 - Exit");
int choice = in.nextInt();
switch (choice) {
case 1: System.out.println(catalog.displayAll()); break;
case 2: System.out.println("Display keyword"); break;
case 3: System.out.println("Add item:\nEnter ID: ");
int newId=in.nextInt();
System.out.println("Enter description: ");
String newDesc=in.next();
System.out.println("Enter cost: ");
double newCost=in.nextDouble();
catalog.add(newId, newDesc, newCost); break;
case 4: System.out.println("Remove item"); break;
case 5: System.out.println("Change cost of one item"); break;
case 6: System.out.println("Change cost by %"); break;
case 7: endCatalog=true; break; }
}
}
}
class Catalog
{
final static int MAX = 100;
private CatalogItem[] catalogItems;
int inUse;
public Catalog()
{
catalogItems=new CatalogItem[MAX];
}
public void add(CatalogItem newItem)
{
inUse = 0;
if(inUse<MAX) {
catalogItems[inUse] = newItem;
inUse++; }
}
public void add(int newId, String newDesc, double newCost)
{
CatalogItem newItem = new CatalogItem(newId, newDesc, newCost);
}
/*public void remove(int id)
{
}
public String find(String keyword)
{
}
public void changeCost(int id, double percent)
{
}
public void increaseCost(double percent)
{
}
public String toString()
{
}
public boolean equals(Catalog obj)
{
}*/
public String displayAll()
{
String str = "";
for (int i=0; i<inUse; i++) {
str = str + "\n" + catalogItems[i]; }
return str;
}
}
class CatalogItem
{
private int itemID;
private String description;
private double cost;
public CatalogItem()
{
itemID = 1;
description = " ";
cost = 0.0;
}
public CatalogItem(int newID, String newDesc, double newCost)
{
itemID = newID;
description = newDesc;
cost = newCost;
}
public int getItemID()
{
return itemID;
}
public void setItemID(int newID)
{
itemID=newID;
}
public String getDescription()
{
return description;
}
public void setDescription(String newDesc)
{
description=newDesc;
}
public double getCost()
{
return cost;
}
public void setCost(double newCost)
{
cost=newCost;
}
public String toString()
{
return itemID + ", " + description + ", " + cost;
}
public boolean equals(CatalogItem obj)
{
return false;
}
}

Here's the problem:
public void add(int newId, String newDesc, double newCost)
{
CatalogItem newItem = new CatalogItem(newId, newDesc, newCost);
}
What happens to newItem after it is created?

You call this method to add the catalog item:
public void add(int newId, String newDesc, double newCost)
{
CatalogItem newItem = new CatalogItem(newId, newDesc, newCost);
}
But as we can see, this doesn't actually do anything with the object it creates. Did you mean to have this overload of add() call the other one? That would be a good design.
Also, in the other version of add(), you do this:
inUse = 0;
Since you reset inUse every time add() is called, your array will never contain more than one item. Do you see why this is? You should just take this line out.

There is not items ever added to:
private CatalogItem[] catalogItems;
That is so, because you call only this method:
public void add(int newId, String newDesc, double newCost)
{
CatalogItem newItem = new CatalogItem(newId, newDesc, newCost);
}
And that one will never call method that actually tries to add something to the array:
public void add(CatalogItem newItem)
{
inUse = 0;
if(inUse<MAX) {
catalogItems[inUse] = newItem;
inUse++; }
}
In the long run that method will also not work, because item is always added to the index 0. That is so, because as first thing you always set: inUse = 0.

Related

array in object oriented programming

I'm a beginner in object-oriented programming and this is my first little project.I've heard that here everyone can help you in your code and this is my first time.Anyway, my problem why array doesn't store any value?
Here is the code:
public class Information {
private IT_Members[] member= new IT_Members[10];
private int counter = 0;
Information()
{
for ( int ctr=0;ctr<member.length;ctr++)
{
member[ctr] = new IT_Members ();
}
}
public void Add(IT_Members member)
{
if(counter<10)
{
this.member[counter].setName(member.getName());
this.member[counter].setDeparment(member.getDeparment());
this.member[counter].setPostion(member.getPostion());
this.member[counter].setID(member.getID()+counter);
counter++;
}
else
System.out.println("Add List Full");
}
public void Display()
{
if (counter!=0)
{
for (int ctr=0;ctr<10;ctr++){
System.out.println(this.member[ctr].getName()+
this.member[ctr].getDeparment()+
this.member[ctr].getPostion()+
this.member[ctr].getID());
}
}
else
System.out.println("No member yet!");
}
Here is the Main class:
import java.util.Scanner;
import java.util.Arrays;
public class Interface {
public static void main(String[]args)
{
Scanner in=new Scanner(System.in);
IT_Members input1 = new IT_Members();
Information input2 = new Information();
int x=1;
while(x!=0)
{
System.out.println(" \n[1] Add new student member. \n[2] View members.\nChoose now: ");
int choose = in.nextInt();
switch (choose){
case 1:
System.out.println("Name: ");
input1.setName(in.nextLine());
System.out.println("Deparment: ");
input1.setDeparment(in.nextLine());
System.out.println("Postion: ");
input1.setPostion(in.nextLine());
System.out.println("Student record has been added. ");
break;
case 2:
input2.Display();
break;
}
}
.........................................................................
public class IT_Members {
private String name,deparment,postion;
private int ID=1000;
private int Flag=0;
IT_Members (){
}
IT_Members (String name, String deparment , String postion ,int ID , int Flag){
this.name= name;
this.deparment=deparment;
this.postion=postion;
this.ID=ID;
this.Flag=Flag;
}
public String getName (){
return this.name;
}
public String getDeparment (){
return this.deparment;
}
public String getPostion (){
return this.postion;
}
public int getID (){
return this.ID;
}
public int getFlag (){
return this.Flag;
}
public void setName (String name){
this.name = name;
}
public void setDeparment (String Deparment){
this.deparment = deparment;
}
public void setPostion (String postion){
this.postion = postion;
}
public void setID (int ID){
this.ID = ID;
}
public void setFlag (int Flag){
this.Flag = Flag ;
}
public String toStu()
{
String str = "";
str = "\nName: " + this.name +
"\nDeparment: " + this.deparment +
"\nPostion: " + this.postion +
"\nID: " + this.ID;
return str;
}
}
Please, I'm stuck with this I appreciate any help.
Thanks.
You never call the Add function in the Information class. Therefore you never initialize any of the array elements you then want to display.
You need to add input2.Add(input1) before you print that is has been added.
You have to create every time a new Object and in the end you have to add in the list.
import java.util.Scanner;
import java.util.Arrays;
public class Interface {
public static void main(String[]args)
{
Scanner in=new Scanner(System.in);
Information input2 = new Information();
int x=1;
while(x!=0)
{
System.out.println(" \n[1] Add new student member. \n[2] View members.\nChoose now: ");
int choose = in.nextInt();
switch (choose){
case 1:
IT_Members input1 = new IT_Members();// this need to be here so that every time crete new object
System.out.println("Name: ");
input1.setName(in.nextLine());
System.out.println("Deparment: ");
input1.setDeparment(in.nextLine());
System.out.println("Postion: ");
input1.setPostion(in.nextLine());
input2.Add(input1); // that was missing
System.out.println("Student record has been added. ");
break;
case 2:
input2.Display();
break;
}
}

unable to assign array list to an array of an Object (Java)

So i am trying to make a deal or no deal game the game is not finished yet but the biggest issue i am having is that when i am trying to assign an array list to a array of type cases it seems like it isn't getting assigned.
I tried to debug and after shuffle the output is correct but i am unable to assign the result to the case array so that i can use it in game
Below are my 3 classes upon assigning the outcome i am getting is
The line i am talking about is the method available cases
public class Case {
private int value = 0;
private String face;
/*
* Constructor for type Case
*/
public Case(int value)
{
this.value = value;
}
/*
* Getter and setter methods for instance data
*/
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public String getFace() {
return face;
}
public void setFace(String face) {
this.face = face;
}
}
public class Player {
private String name;
private int age;
private boolean canPlay = false;
private int money = 0;
/*
* Constructor for type Player
*/
public Player(String name, int age) {
super();
this.name = name;
this.age = age;
}
/*
* Getter and Setter methods for all instance Data
*/
public Player(boolean canPlay)
{
this.canPlay = canPlay;
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
public boolean isCanPlay() {
return canPlay;
}
public void setCanPlay(boolean canPlay) {
this.canPlay = canPlay;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
/*
* This method will check if the person playing is at least 18 years old or not
*/
public void checkAge()
{
if(age >= 18)
{
canPlay = true;
System.out.println("Seems like you are old enough to play!");
System.out.println("Let's get started");
}
else
{
canPlay = false;
System.out.println("OH NO! you aren't old enough sadly we won't be able to continue");
}
}
public String toString() {
return "Today's player is "+name+" who is "+age+" old";
}
public static void setupPlayer()throws InputMismatchException
{
String playerName;
int playerAge;
System.out.println("Welcome to the Deal or No Deal game!");
System.out.println("Please state your name:");
Scanner name = new Scanner(System.in);
playerName = name.nextLine();
System.out.println("Welcome "+playerName+" how old are you?");
Scanner age = new Scanner(System.in);
playerAge = age.nextInt();
Player gamePlayer = new Player(playerName, playerAge);
}
public static void Rules()
{
System.out.println("Below listed are the Game Rules\n");
System.out.println("-There are 12 Cases in the game");
System.out.println("-Each case contains a amount of money and you will be "
+ "offered these Cases 1 at a time");
System.out.println("-Upon picking a Case the game will end and you will have a "
+ "chance to walk away with that case");
System.out.println("-If No cases are picked you will get 2 option, to walk away"
+ " with the last Case or take the bankers offer");
System.out.println("-To accept the case type \"Y\" ,to decline it type \"N\"");
}
}
public class SetUpCases {
private Case[] cases = new Case[12];
/*
* This method initializes each object type with an amount which will be the Money in each Case
*/
public void settingUpCases()
{
ArrayList<Integer> myCase= new ArrayList<Integer>();
myCase.add(new Integer(1));
myCase.add(new Integer(50));
myCase.add(new Integer(100));
myCase.add(new Integer(250));
myCase.add(new Integer(500));
myCase.add(new Integer(1000));
myCase.add(new Integer(2500));
myCase.add(new Integer(5000));
myCase.add(new Integer(10000));
myCase.add(new Integer(25000));
myCase.add(new Integer(50000));
myCase.add(new Integer(100000));
/*
* The Shuffle changes which index has what value so game results are different each time played!
*/
Collections.shuffle(myCase);
for(int i = 0; i < cases.length; i++)
{
int value = myCase.get(i);
cases[i] = new Case (value);
System.out.println(cases[i]);
}
}
/*
* Shows which Cases are still available
*/
public void availableCases()
{
for (int k = 0; k < cases.length; k++)
{
System.out.println(cases[k]);
}
}
public void startGame()
{
settingUpCases();
}
}
You are printing case object instead of its value.. use getValue (or getFace) method to print the value (or face). For example
for (int k = 0; k < cases.length; k++)
{
System.out.println(cases[k].getValue());
}
If you want to print both value and face, the best way will be to override the toString method and print these variables there.
The reason you are getting those weird values is not because the assignments aren't working but because you aren't printing the string value of your values. Try the following.
for(int i = 0; i < cases.length; i++){
int value = myCase.get(i);
cases[i] = new Case (value);
System.out.println(Arrays.toString(cases[i]));
}

#override to.String printing out only default constructor java hw

At the end of my for loop, Id like to print out all the objects in the array. I used a generate toString with string builder from Source, however, after the loop is done executing, it prints out the default values of variables Item:
[Item [getPrice()=0.0, getName()=No Name yet., getPriority()=-1.0], Item [getPrice()=0.0, getName()=No Name yet., getPriority()=-1.0], Item [getPrice()=0.0, getName()=No Name yet., getPriority()=-1.0], Item [getPrice()=0.0, getName()=No Name yet., getPriority()=-1.0], Item [getPrice()=0.0, getName()=No Name yet., getPriority()=-1.0], Item [getPrice()=0.0, getName()=No Name yet., getPriority()=-1.0], null]
heres my code
public class Item {
static Item list[]=new Item [7];
public static int x = 0;
public static String setName;
public static double setPrice;
public static int setPrioirty;
private int priority=-1;
private double price;
private String name;
Item(){
priority=-1;
price=0;
name="No Name yet.";
}// default constructor.
public Item(int i, double j, String k) {
setItem(i,j,k); //constructor with 3 arguments.
}
public void setItem (int i, double j, String k){ // setting item with 3 attributes.
setPriority(i);
setPrice(j);
setName(k);
}
public void setName(String k) { //setting individual attributes in item.
// TODO Auto-generated method stub //page 378
name=k;
}
public void setPrice(double j) {//setting individual attributes in item.
// TODO Auto-generated method stub
if (j<0||j>100){
System.out.println("Error: price is too low or high");
}
else
price=j;
}
public void setPriority(int i) {//setting individual attributes in item.
// TODO Auto-generated method stub
priority =((i>=0&&i<7)?i:0);
}
public double getPrice(){
return price;
}
public String getName(){
return name;
}
public double getPriority(){
return priority;
}
public static void add(Item itemObject) {
if (x<7)
{
list[x]=itemObject;
System.out.println("Item added at index " + x);
x++;
}
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Item [getPrice()=").append(getPrice()).append(", ");
if (getName() != null)
builder.append("getName()=").append(getName()).append(", ");
builder.append("getPriority()=").append(getPriority()).append("]");
return builder.toString();
}
}
main
import java.util.Arrays;
import java.util.Scanner;
import java.util.Set;
public class homework3main extends Item {
#SuppressWarnings("static-access")
public static void main(String[] args) {
//item list[]=new item [7]; // array of objects
Scanner keyboard= new Scanner(System.in);
for(int x=1; x<7;x++){
Item itemObject=new Item ();
//Item itemObject=new Item (setPrioirty,setPrice,setName);
//creating new object with 3 variables, name, price, priority
//list[x]=new Item();// is this right?
System.out.println("Enter an item you want to add to your list "+ x);
list[x].setName=keyboard.next();
System.out.println("Enter a price "+x);
list[x].setPrice=keyboard.nextDouble();
System.out.println("Enter the priority of the item "+x);
list[x].setPrioirty=keyboard.nextInt();
//item itemObject=new item (setPrioirty,setPrice,setName);
list[x].add(itemObject);
}
System.out.println(Arrays.toString(list));
My conditional statements dont work either in my Set methods. Cant understand why those dont work, they are pretty straight forward.
you appear to have several structural issues with the code so here is what i think it should be:
import java.util.Arrays;
import java.util.Scanner;
public class Item {
//the properties of an Item
private int priority;
private String name;
private double price;
//default constructer
public Item() {
priority = -1; //fill with default values
price = 0.0;
name = "No name yet";
}
//constructer with all fields given
public Item(int priority, String name, double price) {
this.priority = priority; //there are two instances of each variable
this.name = name; // use 'this.' to distinguish them
this.price = price;
}
// all getters simply will return the corresponding field
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
//priority must be between 0 and 7
if (priority >= 0 && priority <= 7) {
this.priority = priority;
} else {
//otherwise default to 0
this.priority = 0;
}
}
public String getName() {
return name;
}
public void setName(String name) {
//no constraints on the name so simply assign it
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
//price between 0 and 100 inclusive
if (price >= 0) {
if (price <= 100) {
this.price = price;
} else {
//use System.err for errors
// used nested ifs so you can tell if price is to high or low
//otherwise it is a bit ambiguous
System.err.println("Error: price to high");
}
} else {
System.err.println("Error: price to low");
}
}
//your tostring is fine
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Item [getPrice()=").append(getPrice()).append(", ");
if (getName() != null) {
builder.append("getName()=").append(getName()).append(", ");
}
builder.append("getPriority()=").append(getPriority()).append("]");
return builder.toString();
}
//just put your main here
//if you can't then put it in a class but don't sub-class this class
public static void main(String[] args) {
//put your list declaration here
//it doesn't quitemake sense for the Item calss to have a field
//called list in this instance
Item[] list = new Item[7];
Scanner keyboard = new Scanner(System.in);
//i is the most commonly used variable for 'for' loops
for (int i = 1; i <= list.length; i++) {
//create a new item
Item anItem = new Item();
//call your methods on that object to set its fields
System.out.println("Enter an item you want to add to your list " + i);
anItem.setName(keyboard.next());
System.out.println("Enter a price " + i);
anItem.setPrice(keyboard.nextDouble());
System.out.println("Enter the priority of the item " + i);
anItem.setPriority(keyboard.nextInt());
//use the var i for the position
//remember to subtract 1 since arrays start at 0 but i starts at 1
list[i-1] = anItem;
}
System.out.println(Arrays.toString(list));
}
}
In your condition
j < 0 && j > 100
How can j both be smaller than 0 and greater than 100? You need ||.
In your methods
System.out.println("Enter an item you want to add to your list "+ x);
list[x].setName=keyboard.next();
System.out.println("Enter a price "+x);
list[x].setPrice=keyboard.nextDouble();
System.out.println("Enter the priority of the item "+x);
list[x].setPrioirty=keyboard.nextInt();
you are setting the static fields of the Item class, not the fields of the instance. Either use the setters you have or use the constructor. For example
Item itemObject = new Item ();
System.out.println("Enter an item you want to add to your list "+ x);
itemObject.setName(keyboard.next());
System.out.println("Enter a price "+x);
itemObject.setPrice(keyboard.nextDouble());
System.out.println("Enter the priority of the item "+x);
itemObject.setPriority(keyboard.nextInt());
list[x] = itemObject;
You're completely overusing setters by the way. Go through this tutorial.

How to create an Array in the constructor class?

I was create a book inventory program.
I has two classes one is the main class, and the other one is the constructor class name Item.
On the main class, i has create a array (Item[] book = new Item[100]) to store my input.
And in my Item class, i want to create a function below
public boolean addItem(Item[] iArray, String itemCode){
boolean c = false;
for(int i=0; i<iArray.length; i++){
if(iArray[i].getItemCode().equals(itemCode)){
c = true;
}
else{
c = false;
}
}
return c;
}
how to i make that Item[] iArray sync with the book array in main class?
public class Item {
private String itemCode;
private String description;
private int quantity;
private double costprice;
private double sellprice;
private String status = "Available";
private boolean check;
private double discount;
public Item(){
this("A000","default",0,0.00,0.00,0.25,"Available");
}
//construtor with parameter
public Item(String itemCode, String description, int quantity, double costprice, double sellprice, double discount, String status){
this.setItemCode(itemCode);
this.setDescription(description);
this.setQuantity(quantity);
this.setCostprice(costprice);
this.setSellprice(sellprice);
this.setStatus(status);
this.setDiscount(discount);
}
//setter and getter methods
public void setItemCode(String itemCode){
this.itemCode = itemCode;
}
public String getItemCode(){
return this.itemCode;
}
public void setDescription(String description){
this.description = description;
}
public String getDescription(){
return this.description;
}
public void setQuantity(int quantity){
this.quantity = quantity;
}
public int getQuantity(){
return this.quantity;
}
public void setCostprice(double costprice){
this.costprice = costprice;
}
public double getCostprice(){
return this.costprice;
}
public void setSellprice(double sellprice){
this.sellprice = sellprice;
}
public double getSellprice(){
return this.sellprice;
}
public void setStatus(String status){
this.status = status;
}
public String getStatus(){
return this.status;
}
public void setDiscount(double discount){
this.discount = discount;
}
public double getDiscount(){
return this.discount;
}
public void setCheck(boolean check){
this.check = check;
}
public boolean getCheck(){
return this.check;
}
public boolean addItem(Item[] iArray, String itemCode){
boolean c = false;
for(int i=0; i<iArray.length; i++){
if(iArray[i].getItemCode().equals(itemCode)){
c = true;
}
else{
c = false;
numberofobject++;
}
}
return c;
}
public void displaymenu(){
System.out.println("Menu");
System.out.println("1. Add New Item");
System.out.println("2. Search");
System.out.println("3. Edit Details");
System.out.println("4. Edit Quantity");
System.out.println("5. Stop Sell");
System.out.println("6. List");
System.out.println("7. Exit");
}*/
public String toString(){
String msg = "";
msg = this.getItemCode()+"\t\t\t\t"+this.getDescription()+"\t\t\t\t"+this.getQuantity()+"\t\t\t\t"+this.getCostprice()+"\t\t\t\t"+this.getSellprice()+"\t\t\t\t"+this.getDiscount()+"\t\t\t\t"+this.getStatus();
return msg;
}
this is my Item class.
import java.util.*;
public class Driver {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int choice,quantity,NOI=0;
double cprice,sprice,discount;
String itc,name,status = "Available";
boolean check = true;
Item[] book = new Item[100];
Scanner s1 = new Scanner(System.in);
do{
Item display = new Item();
display.displaymenu();
System.out.print("Please Select Menu: ");
choice = s1.nextInt();
if(choice==1){
do{
System.out.print("Please Enter the Item Code: ");
itc = s1.next();
//for(int i=0; i<book.length; i++){
//book[i].addItem(book, itc);
if(display.addItem(book, itc)==true){
System.out.println("the book item code already exist."+NOI);
check = false;
}
else
{
check = true;
} //This is the question where i faced.
//}
}while(check==false);
System.out.print("Please Enter the Description: ");
name = s1.next();
System.out.print("Please Enter the Quantity: ");
quantity = s1.nextInt();
System.out.print("Please Enter the Cost Price: ");
cprice = s1.nextDouble();
System.out.print("Please Enter the Sell Price: ");
sprice = s1.nextDouble();
System.out.print("Please Enter the Discount: ");
discount = s1.nextDouble();*/
book[NOI] = new Item(itc,name,quantity,cprice,sprice,discount,status);
NOI++;
}
when i add the second item, there was a error (Exception in thread "main" java.lang.NullPointerException),
how to solve it?
Your method does not do what you want, because even if you find the item code, the loop continues. You probably want something like this instead:
public boolean addItem(Item[] iArray, String itemCode){
for (Item item : iArray) {
if (item.getItemCode().equals(itemCode)) {
return true;
}
}
return false;
}
Note that the method you posted seems oddly named, because it does not add anything anywhere.
You might also consider using a List<Item> (ArrayList, etc.) instead of an Item[].
I am not sure I understand what you are looking for so if my answer is irrelevant just comment it and I will delete.
I assume you are trying to store information : add new item with its code to an array. But I'm not sure if you're:
trying to insure the uniqueness of your item in the array before inserting it:
maybe you can use a set of codes, it will simplify your problem, just check with .contains() and then add it or not
trying to add it to the list and if it already exist perform something (incrementation of the number of book for the code?)
maybe you can use a HashMap with code as key and book as item.
In your current state, your method addItem does not add anything, just return if your last book in the array matches your code...

Deleting content and displaying all the content in JAVA

I'm here with my classes, my software is almost done after finishing last two things I will continue to GUI development. Anyway, here is my code:
public class Team
{
private String clubName;
private String preName;
private ArrayList<Branch> branches;
public Team(String clubName, String preName)
{
this.clubName = clubName;
this.preName = preName;
branches = new ArrayList<Branch>();
}
public Team() {
// TODO Auto-generated constructor stub
}
public String getClubName() { return clubName; }
public String getPreName() { return preName; }
public ArrayList<Branch> getBranches() { branches = new ArrayList<Branch>(branches);return branches; }
public void setClubName(String clubName) { this.clubName = clubName; }
public void setPreName(String preName) { this.preName = preName; }
public void setBranches(ArrayList<Branch> branches) { this.branches = new ArrayList<Branch>(branches); }
}
public class Branch
{
public ArrayList<Player> players = new ArrayList<Player>();
String brName;
public Branch() {}
public void setBr(String brName){this.brName = brName;}
public String getBr(){return brName;}
public ArrayList<Player> getPlayers() {players =new ArrayList<Player>(players); return players; }
public void setPlayers(ArrayList<Player> players) { this.players =new ArrayList<Player>(players); }
public String toString() {
return "Branches [" + brName + "]";}
}
public class Player
{
private String name;
private String pos;
private Integer salary;
private Integer number;
public Player(String name, String pos, Integer salary, Integer number)
{
this.name = name;
this.pos = pos;
this.salary = salary;
this.number = number;
}
public Player(){}
public String getName() { return name; }
public String getPos() { return pos; }
public Integer getSalary() { return salary; }
public Integer getNumber() { return number; }
public void setName(String name) { this.name = name; }
public void setPos(String pos) { this.pos = pos; }
public void setSalary(Integer salary) { this.salary = salary; }
public void setNumber(Integer number) { this.number = number; }
public String toString() {
return "Player [name=" + name + ", number=" + number + ", pos=" + pos
+ ", salary=" + salary + "]";
}
}
//TEST
String p1,p2;
int a1,a2;
String t, br;
System.out.print("Enter player name : ");
p1 = input.readLine();
System.out.print("Enter player position : ");
p2 = input.readLine();
System.out.print("Enter player salary : ");
a1 = Integer.parseInt(input.readLine());
System.out.print("Enter player number : ");
a2 = Integer.parseInt(input.readLine());
players[pCount].setName(p1);
players[pCount].setPos(p2);
players[pCount].setSalary(a1);
players[pCount].setNumber(a2);
ptmp.add(players[pCount]);
pCount++;
System.out.print("Enter the branch of player : ");
br = input.readLine();
int fff=0;
for(int i = 0; i<brCount;i++)
{
if(br.equals(myBranch[i].brName)==true){
myBranch[i].setPlayers(ptmp);fff=i;}
}
MY FIRST QUESTION : I'm trying to add a player to my system. When a player added I can easily add it to Branch class too and connect them. But I can't do it for Players' club. I mean I want to display which player plays in which club. But I can't do it.
MY SECOND QUESTION : Deleting a player is problem too. When I delete player it should be deleted everywhere. But couldn't figured that out.
In the test, you can see the display function I tried. It works fine for Branch-Player. And I wanna add Team connection too. Team-Branch-Player should be connected.
Q1: It depends how efficiently you want to do your searches.. for now, since you don't store back references you have to first search in which branch is your player and then search which is the club that contains your branch.
With good equals method for your Branch and Player class this is trivial:
for (Team t : teamList)
{
if (t.branches.contains(player))
return true;
}
return false;
But this won't be efficient since you'll have a O(n*m) complexity where n is the team size and m is the average branch size.
If you want something more efficient I'd suggest you to store backreferences inside your classes, you can have your Player class with two attributes
Branch currentBranch
Team currentTeam
and you can set them while you add the player to a branch/team.
Otherwise you can keep a separate HashMap that maps every player to his branch/team. Less memory efficient but quite straightforward.
Q2: to remove the Player from his branch/team you just have to know in which one he stays.. (using the answer to Q1), then before removing from players you just remove it from the corresponding branch/team:
Branch b = findWhichBranch(player);
Team t = findWhichTeam(player);
b.remove(player);
t.remove(player);
players[index] = null;
Of course if branch is implied by team you will just remove it from the branch, since there's no direct association between a player and a team.

Categories