Creating a new instance of a class from another class - java

So I'm stuck on some homework trying to create an instance of the Employee class from my class called records.
public class Employee implements Comparable<Employee>
{
/* instance variables */
private String Name;
private String employeeNumber;
/**
* Constructor for Employee
*/
public Employee(String employNum)
{
super();
this.employeeNumber = employNum;
}
Next I need to create a Record class that will create a HashSet of Employees details, this is where I need help.
public class Records
{
private HashSet employeeSet;
public Records()
{
Set<Employee> employeeSet = new HashSet<Employee>();
}
Then I want it to have a method for adding a new employee and then putting their records in the set.
public enrollEmployee(String num)
{
Employee newEmp = new Employee(num);
employeeSet.add(newEmp);
}
}
I can't get that last bit to create a new employee, it doesn't come out with an error and it compiles correctly. Just no new employee.
*Adding the employeeSet.add(newEmp); caused a compiler warning and that method won't run due to a NullPointerException, probably because the employee isn't actually created.
For more info, when I create an employee the name should come out as "null" if only an employee number is entered but I still need to store that information.
Edited to update information. There is more detail for the Employee class which I have left out, I'm only supposed to be creating the Records class.
Last update, thank you for the help. After reading the replies this is what I got to work for me.
public class Records
{
private Set<Employee> employeeSet = new HashSet<Employee>();
public Records()
{
}
public void enrollEmployee(String num)
{
Employee newEmp = new Employee(num);
employeeSet.add(newEmp);
}
}

Heres the new solution based on what you are looking for in the comments
public class Record
{
private Set<Employee> employeeSet = new HashSet<Employee>();
public Record()
{
newEmployee("1");
newEmployee("2");
newEmployee("3");
}
public void newEmployee(String employNumber)
{
Employee newEmp = new Employee(employNumber);
employeeSet.add(newEmp);
}
}
The method that you created was never called on... So an employee was never created. Therefore, by calling on the newEmployee method in the Record Constructor, a new employee is created

Related

ArrayList is being overwritten

I am trying to add a new train to my arraylist but upon adding the train, the existing content of the arraylist gets overwritten by the new input. This results in having only one item in the arraylist without being able to add more without overwriting the other. As I do not quite know what the source of this problem in the code is, I came looking for help here.
Within this class the train is being made:
public class RCommand extends RBaseListener {
Company mycompany = new Company("traincompany");
#Override
public void enterNewtraincommand(RParser.NewtraincommandContext ctx) {
System.out.println("Now creating new train " + ctx.getText());
mycompany.addTrainTo(new Train(ctx.getChild(2).toString()));
System.out.println(mycompany.getTrains().size());
}
}
In this class the train is supposed to be added to the list.
public class Company{
private String name;
List<Train>trains = new ArrayList<Train>();
public void addTrainTo(Train train) {
trains.add(train);
for (Train t :trains) {
System.out.println(t.getName());
}
}
}
Simply test for your class Company to see if if work
public class Test {
Company company = new Company();
public static void main(String[] args) {
Test test = new Test();
test.start();
}
private void start() {
System.out.println("IT work");
company.addTrainTo(new Train("One"));
System.out.println("End first add");
company.addTrainTo(new Train("two"));
System.out.println("End second add\n");
System.out.println("Follow example will not work");
company = new Company();
company.addTrainTo(new Train("One"));
System.out.println("End first add");
company = new Company(); // <--- create the ERROR
company.addTrainTo(new Train("two"));
System.out.println("End second add");
}
}
Suppose we have train as is:
public class Train {
private String name;
public Train(String name) {
this.name = "Train" + name;
}
public String getName() {
return name;
}
}
Output is:
IT work
Train One
End first add
Train One
Train two
End second add (it work fine)
Follow example will not work
Train One
End first add
Train two
End second add<- we miss the first train because we recreate the company instance
So it work.
So the error is not in this class Company.
Check if the caller of Company recreate the class Company before adding new train
Check class train if it has something strange (static attribute for name or similar)
Looks like new "trains" object is being created for each addition. After adding, try to print the address of "trains" object to find out for sure. You can print the address by System.out.println("trains address is: " + trains)
You did't pass for us all your code required but I think, you should create a Company constructor with your train List.
Something like that:
public class Company{
private String name;
List<Train>trains;
public Company(String name, List<Train> trains){
this.name = name;
this.trains = trains;
}
...
}
Then in your RCommand class use your new Constructor
Company mycompany = new Company(new ArrayList<Train> ,"traincompany");
And it will be fine. Your mistake in code is creating new trains list every time by calling new operator.

Adding String object to ArrayList

I am trying to create a method in my code that searches through an array list (in my case customerList, which contains Customer objects) and will add something new to it if that something isn't found in the ArrayList...
Here is how I have it all set up....
public class CustomerDatabase {
private ArrayList <Customer> customerList = null;
public CustomerDatabase() {
customerList = new ArrayList<Customer>();
}
and this is the method I'm trying to make. I'm trying to get it so that it will add a Customer with given name "n" to the end of the ArrayList if it isn't found in the ArrayList...
public void addCustomer(String n)
{
for(Customer c:customerList)
if (!customerList.contains(n))
customerList.add(n);
}
I'm aware that something is wrong with the whole .add and then a String thing but I'm not sure where I went wrong. Any input would be great!
You're confusing your Customer class with its name property. You can't check if a list of Custom contains a String because it never will. But you can check if any customers in the list have the property you're looking for. If you don't find any, then you have to construct a new object with that string:
public void addCustomer(String name) {
for (Customer c : customerList) {
if (c.getName().equals(name)) {
// duplicate found
return;
}
}
// no duplicates; add new customer
customerList.add(new Customer(name));
}
This assumes Customer has a constructor Customer(String name) and a method String getName(). Adapt as necessary.
Customer is a class and you made an array list of Customer class type.there is no direct way to compare name(String) with Customer class object.
You should change your code like-
public void addCustomer(String name) {
for (Customer c : customerList) {
if (!c.getName().equals(name)) {
Customer c=new Customer();
c.setName(name);
customerList.add(c);
}
}
}
And in Customer Class
Class Customer{
private String name;
//getter and setter method for name.
}

Using a method from one class into a set

I'm having problems getting a method from one class to work if I put the objects into a set.
So I have
public class Employee {
/* instance variables */
private String firstName;
private String employeeNumber;
public Employee(String employNum) {
super();
this.employeeNumber = employNum;
}
...
public String getFirstName() {
return this.firstName;
}
There is lots of other code which I can post if needed but I'm not allowed to change the Employee class.
So for my code I have to create a class for a Set of Employees which I've done with
public class Records {
public Set<Employee> employeeSet = new HashSet<Employee>();
public Records() {
}
}
Now I need a method that will print the details of all employees in the set. Here is my attempt so far
public void printEmployeeNames() {
for (String employee : employeeSet) {
System.out.println(this.employeeSet.getFirstName());
}
}
The problem I'm having is that it won't compile as it says
"incompatible types"
and highlights employeeSet in
for (String employee : employeeSet)
My other problem is that it can't access the method for getFirstName(). I've tried to isolate the method using
public void printEmployeeNames() {
System.out.println(this.employeeSet.getFirstName());
}
This also won't compile as it states
"cannot find symbol - method getFirstName()".
Edit.
Thanks for the help with this problem, I changed it to this and it worked.
public void printEmployees()
{
for (Employee employee: employeeSet)
{
System.out.println(employee.getFirstName());
}
}
this here makes no sense:
for (String employee: employeeSet)
{
System.out.println(this.employeeSet.getFirstName());
}
since the employeeSet is a Set and sets dont have a method called getFirstName
you have to do:
for (Employee employee: employeeSet) //for every EMPLOYEE in the employeeSet
{
System.out.println(employee.getFirstName()); //from that employ get the name
}
AND create in the Employee class the respective Setter and getters
in this case:
private String firstName;
/**
* #return the employeeNumber
*/
public final String getEmployeeNumber() {
return firstName;
}
That should be
for (Employee employee: employeeSet)
{
System.out.println(employee.getFirstName());
}
Set doesn't have a firstname method. Your employee object have have.
First of all, have you heard of encapsulation? The declaration public Set<Employee> employeeSet is an example of a bad practice, and you should use a private field with some sort of getter. The reason your for loop is raising errors is that you made two mistakes:
employeeSet is a List<Employee>, whereas you are asking for a String when iterating over it. This is incorrect - change the type of employee to Employee.
You are trying to access getFirstName() from your field employeeSet. This won't work, as Set has no such method. I believe you meant to call the method on employee.
Also, you may simplify your code to the following one-liner with Java 8 streams:
public void printEmployeeNames() {
employeeSet.stream().map(Employee::getFirstName).forEach(System.out::println);
}

Java: Queues within A class

I have created a class Book that has a queue of another class I created, Employees as seen below...
class Employee{
String name;
int waiting_time;
int retaining_time;
int priority;
public Employee()
{
this.waiting_time=0;
this.retaining_time=0;
}
//getters and setters ommitted to save space
public void setPriority()
{
priority = waiting_time - retaining_time;
}
public int getPriority()
{
return priority;
}
}
class Book{
String name;
LocalDate start_date;
LocalDate end_date;
boolean archived;
Queue<Employee> Employees ;
public Book()
{
}
//getters and setters for end_date, start_date, archived ommitted to save space
public void setQueue(Queue<Employee> qa)
{
Employees = qa;
}
public Queue<Employee> getQueue()
{
return Employees;
}
When I attempt to add an Employee to the Book's queue...
public static void addEmployee(String aName, ArrayList<Book> booksToCirculate, ArrayList<Employee> employeeArray)
{
Employee anEmployee = new Employee();
anEmployee.setName(aName);
employeeArray.add(anEmployee);
for (Book b : booksToCirculate)
{
b.getQueue().add(anEmployee); //adds employee to each queue, where the error is at
}
}
I receive a NullPointerException error when trying to add an Employee to the queue and I can't seem to figure out why, I've gone through my book, and it appears as if I've done it according to an example of dogs and dogtoy's they had. Any suggestions on where I'm going wrong are much appreciated!
Also, if you have any questions on my code please ask, I'm rather new at classes and objects, but will do my best to explain myself!
It looks you need to create your queue. As you have not, it defaults to null. Hence:
b.getQueue()
is returning null.
So when you call
b.getQueue().add(...)
you are trying to call a method on null which causes the exception.
If this is the case, then the solution would be to create the queue in the Book constructor:
public Book()
{
Employees = new Deque<Employee>(); // pick an implementation of the Queue interface
}
You did not initialize the Queue. You have to initialize it before accessing it, otherwise it's initialized with null by the compiler.
Sonce Queue is an Interface you can't do
Queue<Employee> Employees = new Queue<>(); //won't work, because Queue is an interface
What you could do is use a LinkedList which implemens Queue:
Queue<Employee> Employees = new LinkedList<>();

Infinite loop when trying to populate a list of no more than two Hospitals

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.

Categories

Resources