I need to create my own registry for a school project.
I would like to have
1
room, room
2
room, room
hall, hall
3
room, room
hall, hall
dorm, dorm
But all I am getting is
1
room,room
2
room,hall
hall,hall
3
room,dorm
hall,dorm
dorm,dorm
So somehow the the facility reference got changed somewhere but i have no idea how to fix this. Can anyone help?
These are my codes.
public class registry {
static List<registryRecord> register = new ArrayList<registryRecord>();
public static boolean bind(String name, facility ref){
for(registryRecord r:register){
if(r.name.equals(name)) //check if the name is already binded
return false;
}
registryRecord newRecord = new registryRecord(name, ref);
register.add(newRecord);
for (registryRecord r:register){
System.out.println(r.name +","+ r.ref.name);
}
return true;
}
public class registryRecord {
String name;
facility ref;
public registryRecord(String name, facility ref){
this.name = name;
this.ref = ref;
}
public class server {
public static void main(String args[]) throws Exception{
facility room = new facility("room");
System.out.println(1);
boolean test = registry.bind("room", room);
facility hall = new facility("hall");
System.out.println(2);
boolean test2 = registry.bind("hall", hall);
facility dorm = new facility("dorm");
System.out.println(3);
registry.bind("dorm", dorm);
}
public class facility {
public static String name;
static List<booking> bookings;
public facility(String name){
this.name=name;
this.bookings = new ArrayList<booking>();
}
}
As I suspected, since name is static in facility, it is shared between all instances. This means that it gets overwritten each time you create a new instance.
Just remove static from both your fields, and your program should work fine.
Related
I'm very new to coding and have a strict deadline for this assignment so I couldn't find an explanation I understood very well so I am asking here.
I am makign an instance of my Pokemon class in a another class for my main game. I however need info on how many times a pokemon was defeated in my catch pokemon class as I want a user to only be able to catch a pokemon if they've beat it a certain amount of times. I have no clue how to do this however.
This is how the class is used if it is of any help:
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Battle extends JFrame{
public Pokemon fire = new Pokemon("Charmander", "Fire");
public Pokemon water = new Pokemon("Squirtle", "Water");
public Pokemon plant = new Pokemon("Bulbasaur", "Grass");
public Pokemon ground = new Pokemon("X", "Ground");
I have tried something like Battle.pikachu.toString() in the main class to just test how to access it because that is what someone else told me but the battle part confuses me as I don't think it is actually referrign to anything when in my main class.
You should not define your Pokemon inside a Battle. You should instead pass your Pokemon into this Battle class.
So you should instead define your Pokemon in your Main class:
public class Main {
// Your functions...
private ArrayList<Pokemon> getMyPokemons() {
ArrayList<Pokemon> myPokemonList = new ArrayList<>();
Pokemon fire = new Pokemon("Charmander", "Fire");
Pokemon water = new Pokemon("Squirtle", "Water");
Pokemon plant = new Pokemon("Bulbasaur", "Grass");
Pokemon ground = new Pokemon("X", "Ground");
myPokemonList.add(fire);
myPokemonList.add(water);
myPokemonList.add(plant);
myPokemonList.add(ground);
return myPokemonList;
}
private void triggerBattle() {
ArrayList<Pokemon> myPokemonList = getMyPokemons();
Battle battle = new Battle(myPokemonList);
}
}
And in your Battle class,
public class Battle extends JFrame {
private ArrayList<Pokemon> myPokemons;
// Create constructor to receive your Pokemon
public Battle(ArrayList<Pokemon> myPokemons) {
this.myPokemons = myPokemons;
}
// And in other functions within this class, you can access
// myPokemons list
}
And of course if you need more information related to the Pokemon, you need to refer to #Boycpu suggestion and add more attributes to your Pokemon class.
Do you mean?
public class Pokemon {
private String name;
private String group;
private int defeatedTimes;
public Pokemon(String name, String group, int defeatedTimes) {
this.name = name;
this.pass = group;
this.defeatedTimes = defeatedTimes;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public int getDefeatedTimes() {
return defeatedTimes;
}
public void setDefeatedTimes(int defeatedTimes) {
this.defeatedTimes = defeatedTimes;
}
}
Hello all so I was given this Driver class and was told to make classes to get the driver class working properly. For the most part I think im on the right track but then again im not completely sure because I am new to java. I am getting 2 compiling errors because I have not added a add(temp) method. to be honest im not sure what class to put the method into. for now I have it in the Team class but im getting a compiling error. if anyone can give me some insight it will be well appreciated.
public class Driver{
public static void main(String args[]) throws Exception{
//All information is stored in input.txt and is being
//read in below.
Scanner input = new Scanner(new File("input.txt"));
//Creates a new League and passes in a String signifying
//which league it is.
League american = new League("AL");
League national = new League("NL");
for(int i=0; i<15; i++){
//Creates a new team and adds the current team
//to the american league.
//You can assume there are exactly 15 teams in each league.
Team temp = new Team(input.next());
american.add(temp); // compile error
}
for(int i=0; i<15; i++){
//Creates a new team and adds the current team
//to the national league.
//You can assume there are exactly 15 teams in each league.
Team temp = new Team(input.next());
national.add(temp); // compile error
}
}
my League class
public class League{
private String league;
public League(String League){
league = League;
}
public void setLeagueAmerican(String League){
this.league = League;
}
public String getLeagueAmerican(){
return league;
}
public void setLeagueNational(String national){
this.league = national;
}
public String getLeagueNational(){
return league;
}
public void League( String League){
league = League;
}
}
my Team Class
public class Team
{
// instance variables - replace the example below with your own
private String team;
/**
* Constructor for objects of class Team
*/
public Team(String Team)
{
team = Team;
}
public void setTeam(String Team){
this.team = Team;
}
public String getTeam(){
return team;
}
public String add(League y)
{
return y; //compiling error
}
}
public String add(League y)
{
return y; //compiling error
}
This function returns a String. You are passing the parameter y, which is a League. You then try to return the very same League as if it was a String, which produces the error.
Either change the return type to be a League, or don't return y but a meaningful String (or even y.toString())
In this project the user must enter 1 or 2 hospitals but not 3 or more. So the program starts and I display a menu. If the user presses 1 he must enter a hospital(name and department). After this the program displays the menu again and the user can choose to insert another hospital.
But after that, if I choose to insert another one (which is not permitted) the program accepts it. It seems that every time InsertHospitals() is called from the main class, the value of numberofhospitals (which is a counter counting how many hospitals I entered) equals 0.
public class Hospital {
private String Name, Departments;
private char flag;
private int numberofhospitals;
private Hospital[] ListOfHospitals;
//private Patient[] ListOfPatiens;
//private Doctor[] ListOfDoctors;
//private Examination[] ListOfExaminations;
//private Folder[] ListOfFolders;
public Hospital(String Name, String Departments)
{
this.Name=Name;
this.Departments=Departments;
}
public Hospital()
{
ListOfHospitals = new Hospital[2];
//ListOfPatiens = new Patient[100];
//ListOfDoctors = new Doctor[100];
//ListOfExaminations = new Examination[100];
//ListOfFolders = new Folder[100];
}
public String getName()
{
return Name;
}
public void setname(String Name)
{
this.Name=Name;
}
public String getDepartments()
{
return Departments;
}
public void setdepartments(String Departments)
{
this.Departments=Departments;
}
public void InsertHospitals()
{
if(numberofhospitals==2)
{
System.out.println("You can give only two hospitals!");
}
else
{
String temp = sir.readString("Hospital's Name:");
Name=temp;
String temp1 = sir.readString("Hospital's departments:");
Departments=temp1;
Hospital hospital = new Hospital(Name, Departments);
ListOfHospitals[numberofhospitals]=hospital;
numberofhospitals=numberofhospitals+1;
}
}
}
Your misunderstanding something, the list of hospitals (as mentioned) should not be inside your hospital class. You have to consider your hospital class as a blueprint you are using in your application.
Which means that you need to have a list of hospitals, as a list inside your other application class (which runs the application) and the InsertHospitals method should not be in your hospital class either obviously.
As you add a new hospital in your program, you create a new hospital object and add it to the list of hospitals (fx an arraylist) your keeping as a field value.
Also posssibly make a new constructor with parameters in the hospital class so you can insert the values outside of the class.
Something like this fx.
public class MainApp {
private ArrayList<Hospital> hospitalList;
public static void main(String[] args) {
// Initialize or load it from a file or whatever here.
hospitalList = new ArrayList<Hospital>();
// your code here...
}
public void insertHospital(<insert parameters here to create a hospital>) {
Hospital newHospital = new Hospital(<insert params with new constructor>);
hospitalList.add(newHospital);
}
}
Whatever your problem, your program completely wrong. In insertHospital() your changing Name and Departments fields, and creating new Hospital with those values. When you print Hospital information all hospitals will have the same value.
So I'm creating a student database thing for a school project. My first issue is that upon creating a new student I should see "Application number ### has registered successfully". Now the problem is that we have to have that number generate (### referring to the number) sequentially from 1 every time a new application is recorded. How would I go about doing that?
So far this is what there is but I can't seem to get the number to generate incrementally.
public TestApplication(String Surname, String personalIdNo)
{
if (isValidpersonalIdNo(personalIdNo) == true)
{
Student.add(Surname);
Application.put(personalIdNo, Student);
System.out.println("Application number ### " + "has registered successfully");
}
else
{
System.out.println("Application has failed, Personal id: " + personalIdNo);
}
}
Any help with this would be appreicated.
Since you seem to be using lots of static methods, I believe the best thing for you to do in this case is to create a static field called latestId and a static method called generateId, both in the Student class. Then you can call the generateId method whenever you call Student.add.
However, please note that this solution does not work if your application is multithread.
public class Student {
private static int latestId = 0;
public static int generateId() {
return ++latestId;
}
...
}
You can write a singleton class that will produce the ids for you:
class Generator {
private AtomicInteger count = new AtomicInteger(1);
private static Generator generator = new Generator();
private Generator() { }
public static Generator getInstance() {
return generator;
}
public int generate() {
return count.getAndIncrement();
}
}
Now, when you need to get a new id, you just call the generate method. The AtomicInteger is used because you might need the id from multiple threads and it will make the concurrent access safe.
The singleton Generator provides a single entry point to the id-generating facility.
You can use your storage type to give you the amount of added students that were put into DB.
I don't know what type you use to store your students. If it is hashmap or vector you can use size method to print students count. So I assume if you have Application.put you probably have a field in your Application type that is used to store each student. Then you can add a method like getStudentsCount to it and you should be all set. Since I don't know much about your Application type the above is all assumptions. Below you can find how I would solve that:
import java.util.HashMap;
import java.util.Vector;
class Student{
private String name;
private int personalID;
public Student(String name, int personalID){
this.name = name;
this.personalID = personalID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPersonalID() {
return personalID;
}
public void setPersonalID(int personalID) {
this.personalID = personalID;
}
}
class DB{
private HashMap<Integer, Student> students = new HashMap<Integer, Student>();
public boolean addStudent(Student student) {
Integer studentId = new Integer(student.getPersonalID());
if( !students.containsKey(studentId)){
students.put(new Integer(studentId), student);
return true;
}
else
return false;
}
public int getStudentCount() {
return students.size();
}
}
class Operations{
DB db;
public Operations(DB db){
this.db = db;
}
public boolean addStudent(String name, int personalID){
Student student = new Student(name, personalID);
return db.addStudent( student );
}
}
public class SimpleStudentDB {
public static void main(String [] args){
DB db = new DB();
Operations operations = new Operations(db);
if( operations.addStudent( "Jason", db.getStudentCount()+1) )
System.out.println("Student added successfully. DB contains ###"+db.getStudentCount()+" elements");
else
System.out.println("Operation failed");
}
}
I have situation. I have to create a Sports Club system in JAVA. There should be a class your for keeping track of club name, president name and braches the club has. For each sports branch also there should be a class for keeping track of a list of players. Also each player should have a name, number, position and salary.
So, I come up with this. Three seperate classes:
public class Team
{
String clubName;
String preName;
Branch []branches;
}
public class Branch
{
Player[] players;
}
public class Player
{
String name;
String pos;
int salary;
int number;
}
The problems are creating Branch[] in another class and same for the Player[]. Is there any simplier thing to do this? For example, I want to add info for only the club name, president name and branches of the club, in this situation, won't i have to enter players,names,salaries etc. since they are nested in each other. I hope i could be clear. For further questions you can ask.
Here's a more complete, formal example of your scenario using conventional Accessors/Mutators (getters/setters), constructors, and Lists. The main() method below illustrates how to use your classes.
public class SportsClub
{
public static void main(String[] args)
{
//Create a team without any branches
Team myTeam = new Team("Southpaws", "South");
//Create a new Branch without any players
Branch myBranch = new Branch();
//Add myBranch to myTeam
myTeam.getBranches().add(myBranch);
//Create a new player
Player myPlayer = new Player("Bob", "Center", 120, 3);
//Add myPlayer to myBranch (and therefore myTeam)
myBranch.getPlayers().add(player);
}
}
public class Team
{
private String clubName;
private String preName;
private List<Branch> branches;
public Team(String clubName, String preName)
{
this.clubName = clubName;
this.preName = preName;
branches = new ArrayList<Branch>();
}
public String getClubName() { return clubName; }
public String getPreName() { return preName; }
public List<Branch> getBranches() { return branches; }
public void setClubName(String clubName) { this.clubName = clubName; }
public void setPreName(String preName) { this.preName = preName; }
public void setBranches(List<Branch> branches) { this.branches = branches; }
}
public class Branch
{
private List<Player> players = new ArrayList<Player>();
public Branch() {}
public List<Player> getPlayers() { return players; }
public void setPlayers(List<Player> players) { this.players = players; }
}
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 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; }
}
To answer your question, yes, you can create these objects without populating the Lists with players. The SportsClub.main() above illustrates that.
I would use a List rather than an array since they're (easily) dynamically resizable, but otherwise, you're on the right track.
Think about encapsulation and visibility too. Make all those fields private and provide accessors.
You could create an empty Branch[] array (or better yet - a list) at initialization and add to it later, that way you don't have to enter all the information upon creation - same goes for Player[].
Something like:
public class Team
{
String clubName;
String preName;
private List<Branch> branches;
public Team (String club, String pre) {
clubName = club;
preName = pre;
branches = new LinkedList<Branch>();
}
public void addBranch (Branch branch) {..}
}
public class Branch
{
private List<Player> players;
public Branch () {
players = new LinkedList<Player>();
}
public void addPlayer (Player player) {..}
}
public class Player
{
String name;
String pos;
int salary;
int number;
}
I think that's good. You should probably have methods in the classes to manage your information though--don't try to do anything serious from "Outside" these classes.
to be more specific: All your members should be private and only used/accessed from within the classes--also in general avoid setters and getters, instead ask the class to do things for you.
For example, if you wanted to know how many players were in a branch, you would call branch.countPlayers, not access the Player array to count the players from outside.
If you wanted to know how many players were in a team, you would call team.countPlayers which would call branch.countPlayers for each Branch, sum them up and return the value.
If you wanted to see which branch a player was in, you would call Team.findPlayer(playerName). Team would call branch.hasPlayer(playerName) on each branch until it returned a true, then Team would return the Branch object that returned true.
etc.
Note that this resolves your "Populated or not" issue. If you simply have methods like "hasBranch()", "addBranch()", "removeBranch()" then it doesn't matter how or when you populate the branches array since you control it all within the Team class you can change it's implementation at any time and not change a single line outside that class.
You won't have to enter anything into the players array, nor the branch[]. Provided you make the fields accessible, of have properties, you will be able to put them in however you like.
The class structure looks good to me, but a List would be better so that you don't have to worry about resizing arrays down the road.
Nothing wrong with your classes. I personally would use a strongly-typed List to store the branches and players:
public class Team
{
String clubName;
String preName;
List<Branch> branches;
}
public class Branch
{
List<Player> players;
}
Not sure of the requirement, but you'd probably want to have some kind of identifier or name for each Branch, right?
There's nothing in these classes that forces you to create new players just to instantiate a Branch. The list of Players can remain null or empty until you need them.