Team and players objects Java difficulties - java

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));
}
}
}

Related

How to erase a current object using a function | Java

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.

How to add an Object to an ArrayList

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?

Java target/select class/object - confused (sorry for bad title)

What I have below is producing the desired results by print some employee details along with weekly / monthly wages as appropriate.
However I understand that I should not be inputting data in the constructor as I've done.
I need to prompt for a hours worked value only for "PartTimeEmployees", just not the way I've done it.
I've tested with For-Each loops, Enhanced For loops and using the instanceOf operator.
If I could get some guidance/hints or examples of how to accomplish what is currently being done in the constructor, but in the TestEmployee class instead that would be great.
Mostly I'm not sure how to even describe what I'm trying to achieve. This hinders Googling somewhat. (Help with a better title would also be great)
Thanks in advance.
public class TestEmployee
{
public static void main(String[] args)
{
int size;
Employee[] employees = new Employee[4];
employees[0] = new FullTimeEmployee("Jane", 26000);
employees[1] = new PartTimeEmployee("Jack");
employees[2] = new FullTimeEmployee("Lucy", 52000);
employees[3] = new PartTimeEmployee("Lenny");
for(int i = 0; i < employees.length; i++)
{
employees[i].print();
}
}
}
Class: PartTimeEmployee - Constructor:
public PartTimeEmployee(String thisName)
{
super(thisName);
System.out.println("Please enter the number of hours worked by " + thisName + ": ");
numHours = keyboard.nextInt();
setHours(numHours);
}
If I get your question, below might fit with your need -
First of all create generic Employee class -
class Employee {
private String name;
private int workingHours;
private final boolean IS_PART_TIME_EMP;
public Employee(String name, int workingHours) {
this.name = name;
this.workingHours = workingHours;
this.IS_PART_TIME_EMP = false;
}
public Employee(String name) {
this.name = name;
this.IS_PART_TIME_EMP = true;
}
public String getName() {
return name;
}
public int getWorkingHours() {
return workingHours;
}
public void setWorkingHours(int workingHours) {
this.workingHours = workingHours;
}
public boolean isPartTimeEmployee() {
return IS_PART_TIME_EMP;
}
}
Now you can use it as per your requirement.
Employee[] employees = new Employee[4];
employees[0] = new Employee("Jane", 26000);
employees[1] = new Employee("Jack");
employees[2] = new Employee("Lucy", 52000);
employees[3] = new Employee("Lenny");
Scanner sc = new Scanner(System.in);
for (Employee employee : employees) {
if(employee.isPartTimeEmployee()) {
System.out.println("Please enter working hours by " + employee.getName() + ": ");
int numHours = sc.nextInt();
employee.setWorkingHours(numHours);
}
}
Constructor is not meant for user input.Its main intention is to initialize object of that class.
Instead of doing that in constructor,you can try something like this
employees[1] = new PartTimeEmployee("Jack");
System.out.println("Please enter the number of hours worked by " + employees[1].getName()+ ": ");
numHours = keyboard.nextInt();
employees[1].setHours(numHours);
You most likely will have some logical main loop in your program, like
while(!quit) {
// 1. ask if you want to add part time or full time employee
// 2. ask proper questions
// 3. call correct constructor
}
Writing such small pseudo code algorithm should be self explanatory and get you going.
Step one: presentation of options available for user and reading user input.
Step two: performing actions depending on user input from step 1
Step three: final call to proper constructor depending on results from steps 1 and 2
If I understood your question correctly (which I'm really not sure of) you want to prompt for the employee data in the main method.
In that case I'd use a loop and query the following things:
name of the employee
does the employee work full time? (y/n)
if yes: what is the wage? (assume hours = whatever a full time employee works a day)
if no: how many hours? (and probably the hourly wage as well)
Then use that information to construct an Employee object (I don't see any need for the subclasses here).

Read from file and display in GUI java

I need to read the file in the main than add the red lines (from the file) to an array in the class that stores array objects and display in GUI class. My problem is that nothing goes to the GUI. The getTeamName from Team returns null.
I read the file in
fr = new FileReader("TeamsIn.txt");
Scanner in = new Scanner(fr);
while (in.hasNextLine()){
String line = in.nextLine();
team = new Team(line);
team = teamIn.addTeam(team);
than I add lines to the Team [] array in MatchManager
public Team addTeam( Team teamName)
{
for(int i = 0; i < MAX_TEAMS; i++)
teams[i] = teamName;
return teamName;
}
And i want to display in the GUI
Team t = new Team(teamName);
display = new JTextArea(ROWS, COLUMNS);
display.setEditable(false);
display.setText(t.getTeamName());
JScrollPane scrollPane = new JScrollPane(display);
return scrollPane;
public class Team {
public Team(String teamName){
this.teamName = teamName;
//System.err.println(teamName);
}
public String getTeamName(){
return teamName;
}
public String setTeamName(String tName){
return teamName;
}
But the display.setText(t.getTeamName()); doesnt return anything.
Here's a bit of advice. You may want to restructure your entire program. I know it may seem like "are you for real?", but yes I'm serious. I know you've probably spent a lot of time on it and the last thing you want to do is start over, but the reality of it is, you seem to have a really poor design. Here are some pointer.
Keep the data and view separate. And have some structure to your data. What I mean by that is to keep all the data and data manipulation method in one class.
Here's an example, using ideas from your program
public class MatchManager { // This class holds all the teams
private List<Team> teams = new ArrayList<Team>();
private int countTeam;
private static int MAX_TEAMS=8;
public MatchManager(){
try {
FileReader fr = new FileReader("TeamsIn.txt");
Scanner in = new Scanner(fr);
while (in.hasNextLine()){
String line = in.nextLine();
Team team = new Team(line);
teams.add(team);
}
} catch ( ... ) {}
}
public List<Team> getTeams(){
return teams;
}
}
What the above code does is Once you instantiate the MatchManager, all the teams will get populated.
The JavaBallTournamentGUI class is the one that the program should be launched from. Remember how I talked about keeping the data and view separate. If you think about it, is data supposed to run? No, data is not a program. The GUI is a program though. So run the GUI program getting data from your Model class, the MatchManager.
Something like this.
public class JavaBallTournamentGUI extends JFrame {
MatchManager manager = new MatchManager();
List<Team> teams;
public JavaBallTournamentGUI(){
teams = manager.getTeams();
}
}
Now you can use all the data from the MatchManager in the GUI class.
I notice you instantiating the Team class in a couple different places. That really isn't necessary. Whenever you want to get the data of a team, you can just call it from the list of Teams,
like this
String oneTeam = teams.get(2).getTeamName();
textField.setText(oneTeam);
Do you notice how everything flows more smoothly this way? If you don't, sorry, I tried the best I could to explain. But I hope you get the main points of this. This type of design is much cleaner.
Edit: To print all
If its a JTextArea
for (Team team : teams){
textArea.append(team.getTeamName() + "\n");
}

How to make different instances of a class?

I am making a simple programm that allows people to checkin and out a hotel (for my CS class).
What I need to be able to do is check in a person in a room. There are four rooms. How can i make it so that when someone is checked in, the next person that checks in will check in room 2.
i have the following already:
class Hotel {
Room room1, room2, room3, room4;
Hotel() {
room1 = new Room();
room2 = new Room();
room3 = new Room();
room4 = new Room();
}
static checkIn() {
Scanner sc = new Scanner(System.in);
System.out.print("naam:");
String invoer2 = sc.nextLine();
if (room1.guest == null) {
room1.guestst = invoer2;
System.out.println("Guest " + room1.guest + " gets room 1");
return;
} else {
System.out.println("no rom");
}
return;
}
}
class Room {
static int count;
String guest;
Room() {
guest = null;
count--;
}
Room(String newGuest) {
guest = newGuest;
count++;
}
}
class Guest {
String name;
Guest(String newName) {
name = newName;
}
}
To start off, a Hotel has more than one Room. Depending on what you've learnt as far, you should be using an array to hold all Room instances
Room[] rooms;
Hotel() {
rooms = new Room[4];
}
or an ArrayList
List<Room> rooms;
Hotel() {
rooms = new ArrayList<Room>();
}
See also:
Arrays tutorial
Collections tutorial
Update as per your comment: just check every room if it has a guest until you find a room without a guest (like as in real world!). Pseudo:
if there is no guest in room1, then use room1;
else if there is no guest in room2, then use room2;
else if there is no guest in room3, then use room3;
else if there is no guest in room4, then use room4;
else say "sorry, no rooms left!";
This is by the way easier to do in a simple loop when you use an array.
for each room, check if there is no guest in room, then use room;
if there is no room, then say "sorry, no rooms left!";
Oh, don't forget to make the guest null when s/he leaves the room. This will make the room eligible for reuse.
See also:
if-then-else statements
for statement
class Hotel {
Room room1, room2, room3, room4;
Hotel() {
room1 = new Room();
room2 = new Room();
room3 = new Room();
room4 = new Room();
}
}
If you haven't learned an Array yet.
But an Array (or ArrayList) is a better way to do this.
a comment on the static (also noticed by Ishtar).
If you make checkIn static on the Hotel class (and not instance) you are saying that checkIn is the same over all hotels, and not just your hotel. That suggests that if you have 5 hotels, each with its own rooms, all the rooms are alike. So you could checkIn in hotel 1 and get a room from hotel 2. That's really not what you want to do.
public class Hotel {
// stuff
// Check a guest into this hotel
public Room instanceCheckIn(Guest guest) {
//stuff
}
// Check a guest into one of our hotels. It doesn't matter to which
// particular hotel this room belongs :)
public static Room staticCheckIn(Guest guest) {
//stuff
}
}
Usage:
Hotel instanceHotel = new Hotel();
// check a guest into a room of this hotel (instanceHotel)
instanceHotel.instanceCheckIn(someGuest);
// Check a guest into one of the rooms of our hotels
Hotel.staticCheckIn(someGuest);
// Error: cannot call a non-static method on a class
Hotel.instanceCheckIn(someGuest);
// Technically OK, but incredibly bad taste. You suggest something
// is happening with this hotel (called instanceHotel) but in stead
// your actually working on all hotels together (shared data).
instanceHotel.staticCheckIn(someGuest);
In general it's a very good habit to not use static unless you really need it. It suggests something is broken in your domain model. That does not mean you should not use it, but realize that it has a particular odor. (public static void main(String[] args) is of course a special case).
the next person that checks in will
check in room 2
This can't be done right now. Your hotel only has one room! It should have more, 3 for example:
class Hotel {
Kamer kamer1;
Kamer kamer2;
Kamer kamer3;
Hotel (){
kamer1 = new Kamer();
kamer2 = new Kamer();
kamer3 = new Kamer();
}
}
Or better use arraylist
class Hotel {
ArrayList<Kamer> kamers;
Hotel (){
kamers = new ArrayList<Kamer>();//make room-list
kamers.add( new Kamer() );//add one room
kamers.add( new Kamer() );//add one room
kamers.add( new Kamer() );//add one room
//more?
}
}
If you need a hotel with 3 rooms, just call: new Hotel();.
static void checkIn() {
Kamer k1 = new Kamer(g1.naam);
Why are you making a new room when someone wants to check in? You can't just build a new room if you need one, right? If you remove the static you can use the fields kamer1, kamer2 (or kamers if you used the ArrayList).
void checkIn()
{
if (kamer1.guest==null)
//kamer1 is available!
//
//

Categories

Resources