Constructor with an Array - java

Tody i have tried to code a program, with administrate virtual Footballplayers. Now i have the problem, that i dont know how to initialize an Array of another Class in the Constructer.
This are my declarations for my "Teams"
Manager managerOfBayern = new Manager("Manager1",55,125);
Manager managerOfBvb = new Manager("Manager2",60,122);
Team fcBayern = new Team(managerOfBayern,playerArrFcB,"FcBayern");
Team bvb = new Team(managerOfBvb,playerArrBvb,"Bvb");
Now i want to initialize my Team.
public class Team {
Manager theManager;
Player[] thePlayer;
String name;
public Team(Manager theManager, Player[] thePlayer, String name) {
this.theManager = theManager;
for (int i = 0; i < thePlayer.length; i++) {
thePlayer[i] = thePlayer[i];
}
this.name = name;
}
But how can i correctly initialize an Array (thePlayer)
i hope you guys can help me with this problem.....

What you are doing is almost correct!
just in the the part of array initialization that is the for loop that you are running in the constructor for copying the array, just replace left hand side of the operator '=' with 'this.thePlayer[i]' and you also need to specify the size of the array beforehand to initialize and use it in the for loop i.e the resultant constructor code should be like this
public Team(Manager theManager, Player[] thePlayer, String name) {
this.theManager = theManager;
this.thePlayer = new Player[thePlayer.length];
for (int i = 0; i < thePlayer.length; i++) {
this.thePlayer[i] = thePlayer[i];
//or this.thePlayer[i] = new Player(thePlayer[i]); in case you want true deep copy, then in Player class you make a constructor of this signature(also known as copy constructor) and copy all the properties of Object passed as an argument
}
this.name = name;
}

I don't have the right solution for your problem but I can think for another way if it's good for you. check it out :
For Player class :
private String name;
private int age;
private int height;
public Player(String name, int Age , int height){
this.name=name;
this.age= Age;
this.height = height;
}
public String getName(){
return this.name;
}
public int getAge(){
return this.age;
}
public int getHeight(){
return this.height;
}
#Override
public String toString(){
return this.name +" , "+ this.age +" , "+ this.height;
}
For Manager class :
private String name;
public Manager(String name){
this.name = name;
}
public String getManager(){
return this.name;
}
For Manager class :
Manager theManager;
Player[] thePlayer;
String name;
public Team(Manager theManager, Player[] thePlayer , String name){
this.theManager = theManager;
this.thePlayer = thePlayer;
this.name = name;
}
#Override
public String toString(){
String list = null ;
for (int i = 0;i<thePlayer.length;i++){
list += thePlayer[i].toString()+"\n";
}
return "Team name : " + this.name + "\n Team manager : " + this.theManager.getManager() + "\n Team players : \n" + list;
}
For team class :
Manager theManager;
Player[] thePlayer;
String name;
public Team(Manager theManager, Player[] thePlayer , String name){
this.theManager = theManager;
this.thePlayer = thePlayer;
this.name = name;
}
#Override
public String toString(){
String list = null ;
for (int i = 0;i<thePlayer.length;i++){
list += thePlayer[i].toString()+"\n";
}
return "Team name : " + this.name + "\n Team manager : " + this.theManager.getManager() + "\n Team players : \n" + list;
}
and finally the test class , so if you noticed you don't really need to put that loop inside the team constructor for player :
For test class(main) :
Manager A = new Manager("Flic");
Player P1 = new Player("Robert Levandowski",32,182);
Player P2 = new Player("David Alaba",32,179);
Player P3 = new Player("Joshoa Kimmich",23,175);
Player[] Aplayers = {P1,P2,P3};
Team B = new Team(A , Aplayers ,"FcBayern");
System.out.println(B.toString());
}
And I'm a barcelona fan by the way hahaha still want the revenge for that 8-2 have a great day !

Related

Getting max value from an arraylist of objects

I have an arraylist called cities with objects City from another class, and this object contains both the name of said city but also population. In one method I wanna sum all city populations, aka get the population of the country, however I'm getting an exception in .parseLong method the way I'm doing it. In another one, I wanna check what city has the largest population, but I'm not getting anything when I print and don't know how to fix it. Basically I don't know how to get the value of the objects inside the arraylist. Commented where I have issues for better understanding. Help's appreciated!
public class Country {
private String name;
private City capital;
private int pop;
private ArrayList<City> cities;
public Country(String name, Cidade capital, int pop) {
this.name = name;
this.capital = capital;
this.pop = pop;
cities = new ArrayList<>();
cities.add(capital);
}
public long getTotalPop(){
String c = null;
Iterator<City> iter = cities.iterator();
while(iter.hasNext()){
c += iter.next();
long s = Long.parseLong(c); //giving exception here
System.out.println(s);
return s;
}
return 0;
}
public City getLargest(){
for(City city: cities){
if(city.getPop()>city.getPop()){ //method is fine but if is very wrong since am not sure what to compare to
return city;
}
}
return null;
}
}
public class City {
private String name;
private int pop;
public City(String name) {
this.name = name;
}
public City(String name, int pop) {
this.name = nome;
this.pop = pop;
}
public String getName() {
return name;
}
public int getPop() {
return pop;
}
public void setName(String name) {
this.name = name;
}
public void setPop(int pop) {
this.pop = pop;
}
}
About your Methode getTotalPop()
c should be a long variable and in initialized to 0 because now you are trying to increment a string which is impossible.
you are iterating about a list of cities so iter.next() will give you a city but you want the population of this city so call c += iter.next().getPop();
You don't have to use an iterator. It is okay but you won't get a benefit in this case. My recommendation use a enhanced for/foreach loop.
So use this(iterator):
public long getTotalPop(){
long result = 0;
Iterator<City> iter = cities.iterator();
while(iter.hasNext()){
result += iter.next().getPop();
}
return result;
}
or this(enhanced for/foreach loop):
public long getTotalPop(){
long result = 0;
for (City city : cities) {
result += city.getPop();
}
return result;
}
About your Methode getLargest()
There are some ways to do the job you could use an variable largest pop initialized to 0 and compare each City population with this variable and set it to the pop if it is greater. Or set your pop of the first City as the value to be compared.
With first City:
public City getLargest() {
if (!cities.isEmpty()) {
City largest = cities.get(0);
for (int i = 1; i < cities.size(); i++) {
City city = cities.get(i);
if (largest.getPop() < city.getPop()) {
largest = city;
}
}
return largest;
}
return null;
}
Furthermore because you don't initialize cities in the construtor other than to the new ArrayList don't do that in the constructor but like this:
private List<City> cities = new ArrayList<>();
public Country(String name, City capital, int pop) {
this.name = name;
this.capital = capital;
this.pop = pop;
this.cities.add(capital);
}
At last why is the pop of the country not the same as the pop of all of the cities it has? It would make totaly sense to initialize pop to the result of getTotalPop()

How can I create a new object every time my program loops?

How my program is set up is that my code runs and allows the user to create a new movie object which is then stored to the constructor. It then gives the option to create a new movie which is then stored in the same movie object, which ultimately overwrites the previous movie object that was created. Many implementation go about putting the object creation in a loop, but this asks for all the multiple values to be stored into multiple objects all at once, I'm not looking to do that. I'm not sure how to go about solving this.
Here's my code
Movie class
public class Movie {
private int id;
private String name;
private String description;
private String[] genre;
private String[] actors;
private String[] language;
private String countryOfOrigin;
private Map<String, Integer> ratings;
Movie() {
}
//Constructor
public Movie(int id, String name, String description, String[] genre, String[] actors, String[] language, String countryOfOrigin, Map<String, Integer> ratings) {
this.id = id;
this.name = name;
this.description = description;
this.genre = genre;
this.actors = actors;
this.language = language;
this.countryOfOrigin = countryOfOrigin;
this.ratings = ratings;
}
//setters
public void setid(int id) {
this.id = id;
}
public void setname(String name) {
this.name = name;
}
//getters
public int getId() {
return id;
}
public String getName() {
return name;
}
#Override
public String toString() {
return "\nMovie Id: " + id + " \nMovie Name: " + name + "\nMovie Description: " + description + "\nMovie Genre(s): " + Arrays.toString(genre) + "\nMovie Actor(s): " + Arrays.toString(actors) + "\nMovie Language(s): " + Arrays.toString(language) + "\nCountry of Origin: " + countryOfOrigin + "\nRatings: " + ratings +"";
}
}
Main class
public class Main {
// --- Private global scanner initialization --- //
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) throws Exception {
while (loopAgain) {
Random rand = new Random();
int id = rand.nextInt(MAX);
System.out.println("\nCreate Poll");
System.out.println("\nEnter the Movie Name: ");
String name = input.nextLine();
Movie movie1 = new Movie(id, name, description, genre, actors, language, countryOfOrigin, mapRatings);
System.out.println("Create new movie? (y/n): ");
String answer = input.nextLine();
if (answer.equals("y") || answer.equals("Y")) {
loopAgain = true;
}
}
}
}
You can store the movie objects in some kind of container after you create them. So you can use an ArrayList for example
ArrayList<Movie> movies= new ArrayList<Movie>();.
You can put this above your while loop. Then after you create the object you can add it into the container such as movies.add(movie1) you can put this right under where you called the constructor. Later on to access the object, you can use movies.get(index)

Why is there multiple output when I call from an arraylist?

import java.util.ArrayList;
class BryanList{
public static void main (String [] args)
{
ArrayList<String> alist=new ArrayList<String>();
alist.add("Bryan");
alist.add("18");
alist.add("Chicken Rice");
for (int i = 0; i <= alist.size(); i++) {
System.out.println ("My Name: "+alist.get(i));
System.out.println ("Age: "+alist.get(i));
System.out.println ("Favourite food: "+alist.get(i));
}
}
}
How come its not just displaying just one output instead there's 3 of the same output? Does anyone have any solution for this? Thanks.
If you want one time output then use generics class structure.
Create one class which you want to save records.
class Menu {
public int age;
public String name;
public String favFood;
}
You can create getter/setter method if you need. Otherwise just declare variables with public keyword.
Create one ArrayList which will store object of Menu class.
ArrayList<Menu> alist = new ArrayList<Menu>();
Menu menu = new Menu();
menu.name = "Bryan";
menu.age = 18;
menu.favFood = "Chicken Rice";
alist.add(menu);
Print output
for (int i = 0; i <= alist.size(); i++) {
Menu menu = alist.get(i);
System.out.println("My Name: " + menu.name);
System.out.println("Age: " + menu.age);
System.out.println("Favourite food: " + menu.favFood);
}
I updated your class with your requirement, please check.
class BryanList {
public static void main(String[] args) {
ArrayList<Menu> alist = new ArrayList<Menu>();
Menu menu = new Menu();
menu.name = "Bryan";
menu.age = 18;
menu.favFood = "Chicken Rice";
alist.add(menu);
for (int i = 0; i <= alist.size(); i++) {
Menu menu = alist.get(i);
System.out.println("My Name: " + menu.name);
System.out.println("Age: " + menu.age);
System.out.println("Favourite food: " + menu.favFood);
}
}
}
class Menu {
public int age;
public String name;
public String favFood;
}
Happy coding :)
Your loop check is happening on alist.size() which is in your case 3.
Now, in each iteration, it's printing alist.get(i) 3 times.
Suggestion:
Use POJO and add it to your list.
public class Person{
String name;
int age;
String favFood;
public getName(){
return name;
}
public getAge(){
return age;
}
public getFavFood(){
return favFood;
}
public setName(String name){
this.name = name;
}
public setName(int age){
this.age = age;
}
public setName(String favFood){
this.favFood = favFood;
}
}
And now, your code will work with simple modification.
public static void main (String [] args){
ArrayList<String> alist=new ArrayList<String>();
Person person = new Person();
person.setName("Bryan");
person.setAge(18);
person.setFavFood("Chicken Rice");
// If you want multiple person to add, you need to use loops, and that way you can keep creating person objects and add them to list.
// Suggesting, use separate method for that logic.
alist.add(person);
for (int i = 0; i <= alist.size(); i++) {
Person p = alist.get(i);
System.out.println ("My Name: "+ p.getName());
System.out.println ("Age: "+ p.getAge());
System.out.println ("Favourite food: "+ p.getFavFood());
}
}
Because your printing codes in a For loop. And loop is running 3 three times
alist.size()
means 3, you have 3 item in that list.
This can be your object class:
public class Table {
int age;
String name;
String food;
public Table(int age, String name, String food) {
this.age = age;
this.name = name;
this.food = food;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getFood() {
return food;
}
public void setFood(String food) {
this.food = food;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And fill arraylist with your object:
public static void main(String[] args) {
ArrayList<Table> alist = new ArrayList<>();
// this is how you fill
alist.add(new Table(18, "Bryan", "Rice");
for (int i = 0; i <= alist.size(); i++) {
System.out.println("AGE: " + alist.get(i).age);
//other stuff
}
}
import java.util.ArrayList;
public class HelloWorld {
public static void main(String []args) {
ArrayList<String> alist_name=new ArrayList<String>();
ArrayList<String> alist_value=new ArrayList<String>();
alist_name.add("My Name: ");
alist_name.add("Age: ");
alist_name.add("Favourite food: ");
alist_value.add("Bryan");
alist_value.add("18");
alist_value.add("Chicken Rice");
for (int i = 0; i < alist_name.size(); i++) {
System.out.println (alist_name.get(i)+alist_value.get(i));
}
}
}

Getting same value of a member variable in java

I wrote a test program in java in which the object has 3 parameters:
id, name and age.
The name and age are initialised using constructor but id should be incremented automatically from the last id. (and it should start from 1 for 1st created object).
I used id as static variable to achieve the same.
import java.util.*;
class Test
{
private static int id = 1;
private int age;
private String name;
public Test(String name, int age)
{
this.id = id;
this.age = age;
this.name = name;
id++;
}
public String toString()
{
return id + " " + name + "," + age;
}
public static void main(String args[])
{
Test c1 = new Test("A", 12);
Test c2 = new Test("B", 32);
Test c3 = new Test("C", 58);
Test c4 = new Test("D", 17);
Test c5 = new Test("E", 42);
ArrayList<Test> testList = new ArrayList<Test>();
testList.add(c1);
testList.add(c2);
testList.add(c3);
testList.add(c4);
testList.add(c5);
for(int i = 0; i < testList.size(); i++)
System.out.println(testList.get(i).toString());
}
}
But in the output I am getting same id for all the test objects.
Can anyone please explain why this is happening ?
Any help will be highly appreciated.
A static variable means that the variable is shared between all the instances of the given class, if you change the value of a static variable in one of the instances it will be changed in all.
What you want to accomplish probably is doable in the next way:
class Test
{
public static int counter = 1;
private int id;
private int age;
private String name;
public Test(String name, int age)
{
this.id = counter;
this.age = age;
this.name = name;
counter++;
}
public String toString()
{
return id + " " + name + "," + age;
}
....
Make the counter public, you might actually need to reference it from outside the class instance, or if you cannot afford to expose it as public make it private and create a static getter for it which will allow you to get the current id counter from outside the class.
Another option is to use the Factory Pattern but probably that is not needed for this particular case.

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