Deleting content and displaying all the content in JAVA - 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.

Related

Constructor with an Array

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 !

How to modify code to add a quit option in the menu and keep it looping until it is called?

I am working on a Java text-based adventure game and want to change my code to add a Quit option as a fourth item and keep it looping until the user chooses to quit based on the respective choice. I originally had it so that it would run 10 times inside a while loop, but I decided I wanted the user to have control when they want to quit and end the program.
Here is what I have so far:
Game.java
public class Game {
private static Room library, study, ballroom, kitchen;
private static Room currentLocation;
public static void main(String[] args) {
initialSetupGame();
int rounds = 10;
while(rounds > 0) {
printNextRooms();
int nextRoomIndex = getUserRoomChoice();
Room nextRoom = getNextRoom(nextRoomIndex);
updateRoom(nextRoom);
rounds--;
}
}
public static void initialSetupGame() {
// Instantiate room objects of type Room
library = new Room("Library");
study = new Room("Study");
ballroom = new Room("Ballroom");
kitchen = new Room("Kitchen");
// Connect the objects to each other
library.addConnectedRoom(study);
library.addConnectedRoom(ballroom);
library.addConnectedRoom(kitchen);
study.addConnectedRoom(library);
study.addConnectedRoom(ballroom);
study.addConnectedRoom(kitchen);
ballroom.addConnectedRoom(library);
ballroom.addConnectedRoom(study);
ballroom.addConnectedRoom(kitchen);
kitchen.addConnectedRoom(library);
kitchen.addConnectedRoom(ballroom);
kitchen.addConnectedRoom(study);
// Prompt user for a name
Scanner input = new Scanner(System.in);
System.out.print("Please enter your name: ");
String playerName = input.nextLine();
System.out.println(playerName + "? Wow, that's a neat name!"
+ "\nWelcome to Aether Paradise, a game where you can explore"
+ " the the majestic hidden rooms of Aether. Let's begin!");
// Set the player to start in the library
currentLocation = library;
System.out.println(currentLocation.getDescription());
}
public static void printNextRooms() {
// Lists room objects as menu items
System.out.println("Where would you like to go next?");
currentLocation.printListOfNamesOfConnectedRooms();
}
public static int getUserRoomChoice() {
Scanner input = new Scanner(System.in);
System.out.println("{Select a number): ");
int choice = input.nextInt();
return choice - 1;
}
public static Room getNextRoom(int index) {
return currentLocation.getConnectedRoom(index);
}
public static void updateRoom(Room newRoom) {
currentLocation = newRoom;
System.out.println(currentLocation.getDescription());
}
}
Room.java
public class Room {
private String name;
private String description;
private ArrayList<Room> connectedRooms;
public Room(String roomName) {
this.name = roomName;
this.description = "";
connectedRooms = new ArrayList<>();
}
public Room(String roomName, String roomDescription) {
this.name = roomName;
this.description = roomDescription;
connectedRooms = new ArrayList<>();
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
// Add connected room to the array list
public void addConnectedRoom(Room connectedRoom) {
connectedRooms.add(connectedRoom);
}
public Room getConnectedRoom(int index) {
return connectedRooms.get(index);
}
public int getNumberOfConnectedRooms() {
return connectedRooms.size();
}
// Print the connected rooms to the console
public void printListOfNamesOfConnectedRooms() {
for(int index = 0; index < connectedRooms.size(); index++) {
Room r = connectedRooms.get(index);
String n = r.getName();
System.out.println((index + 1) + ". " + n);
}
}
}
Use java.util.Scanner to read input and check the entered value:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
initialSetupGame();
String reply;
do {
printNextRooms();
int nextRoomIndex = getUserRoomChoice();
Room nextRoom = getNextRoom(nextRoomIndex);
updateRoom(nextRoom);
System.out.print("Would you like to continue? [Y]es/[N]o");
reply = input.nextLine().toLowerCase();
} while ('y' == reply.charAt(0));
}

How to get the Total points for each team in a Tournament Game and get the winner

We want to design a simple tournament that consist of teams with name and citizenship. In this tournament, a set of matches is organized between invited teams and each match opposes two teams. The team with the highest score wins the match. If the result of the match is draw each team gets 1 point, the winning team gets 2 points and no point for the loser. We would like to get the total of points of a team in a tournament to know the winner. The winner is the one with the highest points.
So we managed to create three classes: Team, Match and Tournament and the main class.
In the main class we have this
public class ProgramTournaments {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
//Defining each team
Team frTeam, inTeam, cnTeam;
//Creation of three objects (Teams)
frTeam = new Team("French Blue Team", "French"); // New Means I want to create an Object (frTeams)
inTeam = new Team("Indian Blue Team", "India");
cnTeam = new Team("Chinese Red Team", "China");
//Create a new Tournament
Tournament tournament = new Tournament();
//Invite teams to the tourname
tournament.inviteTeam(frTeam);
tournament.inviteTeam(inTeam);
tournament.inviteTeam(cnTeam);
//Add matches to Tournament
Match m1 = new Match(frTeam, inTeam, true);
Match m2 = new Match(frTeam, cnTeam, true);
Match m3 = new Match(inTeam, cnTeam, true);
tournament.addMatch(m1);
tournament.addMatch(m2);
tournament.addMatch(m3);
//Check If all matches Have been Pleayed
tournament.allMatchPlayed();
}
}
In the team class we did this
public class Team {
//Defining the attributes
private String name; //Private means it is limited only to this Class (team)
private String citizenship;
public String getName() {
return name;
}
public String getCitizenship() {
return citizenship;
}
// Constructor inorder to initialized values
public Team (String name, String citizenship){
this.name = name; //Initializing name of team
this.citizenship = citizenship; //Initializing name of Citizenship of team
}
//Printing to strings
#Override
public String toString() {
return "Team{" + "name=" + name + ", citizenship=" + citizenship + '}';
}
}
In the Match class we did this
public class Match {
private Team team1, team2;
private int scoreTeam1;
private int scoreTeam2;
private int pointTeam1, pointTeam2;
boolean play;
//Constructor
public Match(Team team1, Team team2, boolean play) {
this.team1 = team1;
this.team2 = team2;
this.scoreTeam1 = generateRandomScore();
this.scoreTeam2 = generateRandomScore();
this.play = play;
}
//All Methods
public int getScoreTeam1() {
return scoreTeam1;
}
public void setScoreTeam1(int scoreTeam1) {
this.scoreTeam1 = scoreTeam1;
}
public int getScoreTeam2() {
return scoreTeam2;
}
public void setScoreTeam2(int scoreTeam2) {
this.scoreTeam2 = scoreTeam2;
}
public Team getTeam1() {
return team1;
}
public void setTeam1(Team team1) {
this.team1 = team1;
}
public Team getTeam2() {
return team2;
}
public void setTeam2(Team team2) {
this.team2 = team2;
}
public boolean isPlay() {
return play;
}
public void setPlay(boolean play) {
this.play = play;
}
//Generate Random Score
private int generateRandomScore() {
Random random = new Random();
return random.nextInt(5);
}
public boolean draw() {
if (scoreTeam1 == scoreTeam2) {
pointTeam1 = 1;
pointTeam2 = 1;
return true;
}
return false;
}
public Team matchWinner() {
if (scoreTeam1 > scoreTeam2) {
pointTeam1 = 2;
pointTeam2 = 0;
return team1;
} else {
pointTeam2 = 2;
pointTeam1 = 0;
return team2;
}
}
}
In the Tournament Class we did this
public class Tournament {
private List<Team> ListOfTeams = new ArrayList<>();
private List<Match> ListOfMatches = new ArrayList<>();
//Methods
public void inviteTeam(Team team) { //Inviting Teams
ListOfTeams.add(team);
}
public void addMatch(Match m) {
ListOfMatches.add(m);
}
public boolean allMatchPlayed() {
for (Match match : ListOfMatches) {
if (match.isPlay() == false) {
return false;
}
}
return true;
}
public void tournamentWinner(){
for (Match match : ListOfMatches){
match.decideResult();
}
Comparator <Team> team = new Comparator<Team>(){
#override
public int compare(Team t1, Team t2){
return t1.getScore() - t2.getScore();
}
};
Collections.sort(ListOfTeams, t);
System.out.println("The winner of the tournament is: " + ListOfTeams);
}
}
So please, we are stuck at trying to implement the total points for each teams and to get the winner based on the total points
I would advice to move points member variable from Match to Team. The reason being that each team will have some points at any point of time, so it makes sense that each team has a points field.
Now you would make the following changes to the methods
Team.java
public class Team {
private int points;
// getters and setters for points
/* Rest of your class */
}
Match.java
We should combine your draw() and matchWinner() to one method say decideResult(), as own their own they make no sense.
public void decideResult() {
if (scoreTeam1 == scoreTeam2) {
team1.setPoints(team1.getPoints() + 1);
team2.setPoints(team2.getPoints() + 1);
} else if (scoreTeam1 > scoreTeam2) {
team1.setPoints(team1.getPoints() + 2);
} else {
team2.setPoints(team2.getPoints() + 2);
}
}
To find the winner you can just fetch the score from the respective Team object. For eg : frTeam.getPoints() and compare this with another countries .getPoints()

How to declare an object array length within another object

I am trying to create a program that has 3 Objects; Hotel, Room and Bed. Object Bed will hold information about the bed. Object Room will hold information about the room including how many beds it contains. Object Hotel will contain information about how many Rooms it contains.
my code for the Hotel class looks like this
public class Hotel {
private String name;
private boolean HasVacency = false;
public int numberOfRooms;
Room[] rooms = new Room[numberOfRooms + 1];
public Hotel() {
}
public void setRoom(int numberOfRooms) {
this.numberOfRooms = numberOfRooms;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
And the code for the test class where i create the hotel and declare the values looks like this
public static void main(String[] args) {
HotelTest t = new HotelTest();
t.getHotelInfo();
}
public void getHotelInfo() {
Hotel test = new Hotel();
int numberOfRooms;
int numberOfBeds;
String size;
Scanner input = new Scanner(System.in);
System.out.println("what is the name of the hotel");
String name = input.next();
test.setName(name);
System.out.println("how many rooms does the hotel have");
numberOfRooms = input.nextInt();
test.setRoom(numberOfRooms);
System.out.println(test.rooms.length);
for( int i = 0; i< test.numberOfRooms + 1; i++) {
System.out.println("how many beds does room " + (i + 1) + " have");
numberOfBeds = input.nextInt();
System.out.println(i);
test.rooms[i].setNumberOfBeds(numberOfBeds);
}
}
however i keep getting a null pointer when i try to set the value for the number of rooms in test. Sorry for the messy code
A few things to look at here. Your code breaks encapsulation (you have public members of your hotel class being accessed by other classes); you could make use of constructors to make things a bit neater; look at creating the hotel from its components upward instead of a top-down approach. I've included some sample code based on yours.
public class Hotel {
private final List<Room> rooms;
private final String name;
// constructor to initialize hotel with name and number of rooms
public Hotel(String name, List<String> rooms) {
this.name = name;
this.rooms = rooms;
}
public Room[] getRooms() {
return this.rooms;
}
public String getName() {
return this.name;
}
}
public class Room {
private final int beds;
// constructor to initialize a room with the number of beds it needs
public Room(int beds) {
this.beds = beds;
}
public int getBeds() {
return this.beds;
}
}
public void getHotelInfo() {
Scanner input = new Scanner(System.in);
System.out.println("what is the name of the hotel");
String name = input.next();
System.out.println("how many rooms does the hotel have");
int numberOfRooms = input.nextInt();
List<Room> rooms = new ArrayList<>();
for( int i = 0; i< numberOfRooms; i++) {
System.out.println("how many beds does room " + (i + 1) + " have");
int numberOfBeds = input.nextInt();
// create a room with the number of beds specified and add it to the list of rooms
Room room = new Room(numberOfBeds);
rooms.add(room);
}
Hotel hotel = new Hotel(name, rooms);
// from here on, if you want the hotel's name or its rooms, you can use the appropriate getter methods in the Hotel and Room classes
}
class Hotel {
private String name;
private boolean HasVacency = false;
public Hotel(int numberOfRooms) {
Room[] rooms = new Room[numberOfRooms + 1];
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
I modified your Hotel class. In your old code array of room were being initialized before you are updating numberOfRooms. Create Hotel object like this Hotel test = new Hotel(numberOfRooms);

Inputting data into an object

I'm doing a homework assignment, where we were asked to create a banking system. The first option is to create a customer and to store their information in a customer object. The start of my create_customer() method asks for their name and stores it into a newly create Customer object, but when i call the getName() method, nothing comes back. Here's the initial class Atm which holds all the actions for each option.
import java.util.ArrayList;
public class Atm
{
private ArrayList<Customer> cust;
private int starting_account_number;
private int starting_customer_number;
private String admin_pin;
private int interest_rate;
private int transaction_counter;
ConsoleReader console = new ConsoleReader(System.in);
public Atm() // constructor
{
cust = new ArrayList<>(100);
starting_account_number = 1001;
starting_customer_number = 101;
admin_pin = "abcd";
interest_rate = 5;
transaction_counter = 0;
}
void create_customer()
{
Customer customer = new Customer();
System.out.println("Please input your name: ");
customer.setName(console.readLine());
customer.getName();
while (customer.istrue)
{
System.out.println("Please input a 4 digit alphanumeric PIN: ");
customer.setPin(console.readLine());
if (customer.istrue == false) break;
}
System.out.println("A system generated ID was created for you, it is: ");
String customer_id = String.valueOf(starting_customer_number);
customer.setId(customer_id); // set customer ID
starting_customer_number++; //incrememnt customer ID
System.out.print(customer.getId());
cust.add(customer); //puts the customer object into atm class arraylist
}
Here's the customer class
import java.util.ArrayList;
public class Customer
{
public boolean istrue;
private String name;
private String id; // 3 digits string
private String pin; // 4 digits string
private ArrayList<Account> acct;
private double total_bal; // for all accounts
public Customer() //constructor
{
acct = new ArrayList<>(100);
istrue = true;
name = "NoName";
id = "000";
pin = "0000";
total_bal = 0;
}
// public cal_total_bal() { }
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPin() {
return pin;
}
public void setPin(String pin) {
this.pin = pin;
if (pin.length() != 4)
{
System.out.println("That was not 4 digits, please input a 4 digit alphanumeric PIN: ");
}
else istrue = false;
}
You are calling a method
customer.getName();
But you are not actually doing anything with it.. you might want to print it:
System.out.println(customer.getName());

Categories