Adding elements to an ArrayList from another class - java

I just have this basic code where I need help adding employee data to an ArrayList of another class. I am just writing this code in preparation for an assignment, so don't bash my code too much. Essentially though, i'll be needing to add elements of employees and delete them eventually. But for now, I just need help adding the elements to my other Employee class. =]
public class main {
private static Employee employee;
public static void main(String[] args) {
employee = new Employee(10,10);
System.out.println(employee.toString());
}
}
...............
import java.util.ArrayList;
public class Employee {
public int employeeNum;
public double hourRate;
ArrayList<Employee> Employee = new ArrayList<>();
public Employee(int employeeNum, double hourRate){
this.employeeNum = employeeNum;
this.hourRate = hourRate;
}
public String toString(){
return ""+employeeNum+hourRate;
}
}

Simple Example -
package com;
import java.util.ArrayList;
public class TestPage{
public static void main(String[] args){
Employee emp1, emp2;
emp1 = new Employee();
emp2 = new Employee();
emp1.setName("MAK");
emp2.setName("MICHELE");
emp1.setAddress("NY");
emp2.setAddress("WY");
//and keep putting other information like this
ArrayList<Employee> employee = new ArrayList<Employee>();
employee.add(emp1);
employee.add(emp2);
System.out.println("emp1 name is : " + employee.get(0).getName());
System.out.println("emp2 name is : " + employee.get(1).getName());
System.out.println("emp1 address is : " + employee.get(0).getAddress());
System.out.println("emp2 address is : " + employee.get(1).getAddress());
}
}
class Employee{
String name, address;
int age, salary;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}

It seems like what you're asking is based on one employee having sub-employees and that structurally that probably represents a hierarchy (Some commenters seem to be missing that point). But that's an assumption on my part. Based on that assumption.
A little bit of feedback to start on structure of your main class:
public class main {
public static void main(String[] args) {
Employee employee = new Employee(10,10);
System.out.println(employee.toString());
}
}
It seems to me that there's no reason to have a static instance variable for that root employee instance. You should try to limit the scope of variables where possible. It seems like it could very well be in the main() method's scope.
public class Employee {
public int employeeNum;
public double hourRate;
ArrayList<Employee> employees= new ArrayList<>();
public Employee(int employeeNum, double hourRate){
this.employeeNum = employeeNum;
this.hourRate = hourRate;
}
public String toString(){
return ""+employeeNum+hourRate;
}
public ArrayList<Employee> getEmployees() {
return this.employees;
}
}
It may be better to name your arraylist employees or employeeList. I went with employees in this case because that convention is preferable.
And in relation to your question, ArrayList is pass by reference so you could just add a getter method for the sub-employee list (employees).
To add employees from your main method you could do something like
Employee rootEmployee = new Employee(5, 10.0);
rootEmployee.getEmployees().add(new Employee(6, 5.0));
Or you could add an additional method to Employee like this:
public void addEmployee(Employee e) {
employees.add(e);
}

Related

Generic linked list inside of linked list?

I am trying to write a program which stores information about a person in a linked list. I made a simple person class to store the name, age and addresses in the list. I would also like to store multiple addresses for EACH person, and a fact about the place in another linked list, inside the person class.
So for example, "Tara" can have a home address of "10 Central Ave" and a work address of "5 Willow street" etc. The problem is, I don't know how to have a linked list inside another.
My goal is to check whether the person's name is already on the list, and if so, add another address for them. (So that there is no repeats). I am a beginner and can really use some help.
public class Person {
private String name;
private int age;
public LinkedList <String> adresses;
public Person() {
name = "default";
age = 0;
adresses = new LinkedList<>();
}
public Person(String n, int a) {
name = n;
age = a;
}
public LinkedList<Adress> getAdresses() {
return adresses;
}
public void setAdresses(LinkedList<Adress> adresses) {
this.adresses = adresses;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString() {
return name+" "+age+" "+adresses;
}
}
public class Adress {
public String adress;
public String fact;
public Adress(String a, String f) {
adress = a;
fact = f;
}
public String getAdress() {
return adress;
}
public void setAdress(String adress) {
this.adress = adress;
}
public String getFact() {
return fact;
}
public void setFact(String fact) {
this.fact = fact;
}
}
public class Test {
public static void main(String[] args) {
Person Tara = new Person("Tara",35);
Person Judah = new Person("Judah",28);
Person Mark = new Person("Mark",45);
Person Seth = new Person("Seth",23);
LinkedList<Object> tester = new LinkedList<>();
tester.add(Tara);
tester.add(Judah);
tester.addLast(Mark);
tester.addLast(Seth);
System.out.println(tester);
}
}
How is about to use the next classic data structure for your project?
public class Person {
private String name
private int age;
public List<Address> addresses;
//...
}

How do you fill an array with objects from a different class? deteils below

"This question is for a free online course I am taking. Below is the instructors direction and below that is my answer. I must be solving the problem wrong because the automatic grading system marks it incorrect even though I got the correct output. I believe the instructor wanted me to fill an array in the Main class with objects from the person class and I am unsure how to do that. Please help if you know how to do that or if you have a better idea of what the instructor wanted."
Instructors direction
In your main method, make an array of type Person Fill it with Person objects of the following people and then print the names of each from that array. Each person should be on their own line formatted as shown below.
Fred, 24
Sally, 26
Billy, 15
main.java
class Main {
public static Person[] people;
public static void main(String[] args) {
Person personObject = new Person();
personObject.Person();
}
}
Person.java
public class Person{
public static String[] Person(){
String[] people = {"Fred, 24", "Sally, 26", "Billy, 15"};
for(int i=0; i< people.length; i++){
System.out.println(people[i]);
}
return people;
}
}
It says you need objects and array. So i guess you wanted something like this.
Person.java
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
#Override
public String toString() {
return "Person{" + "name=" + name + ", age=" + age + '}';
}
}
By declaring Person p1 = new Person("Sally",26); you are creating object of class Person. You can use that as many times as you want and create different objects. We use override method toString to print informations about Person. We could also use p1.getName() and p1.getAge()
Main
public static void main(String[] args) {
Person p1 = new Person("Fred", 24);
Person p2 = new Person("Sally", 26);
Person p3 = new Person("Billy", 55);
Person[] people = {p1,p2,p3};
for(Person p : people){
System.out.println(p.toString());
}
}
I think what your professor wants is something like this :)
public class Runner {
public static void main(String args[])throws Exception{
Persons person1 = new Persons();
Persons person2 = new Persons();
Persons person3 = new Persons();
person1.setName("Fred");
person1.setAge("24");
person2.setName("Sally");
person2.setAge("26");
person3.setName("Billy");
person3.setAge("15");
String[] list = {person1.toString(), person2.toString(), person3.toString()};
for (int i = 0; i < list.length; i++) {
System.out.println(list[i]);
}
}
}
public class Persons {
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
#Override
public String toString() {
return name + ", " + age;
}
}

How to add Array Of Objects

How can I Manager class to add an array of Employee objects to the manager class, and create methods to add and remove employees from the Manager
EmployeeTest.java
package com.example;
import com.example.domain.Employee;
import com.example.domain.Engineer;
import com.example.domain.Manager;
import com.example.domain.Admin;
import com.example.domain.Director;
import java.text.NumberFormat;
public class EmployeeTest {
public static void main(String[] args) {
// Create the classes as per the practice
Engineer eng = new Engineer(101, "Jane Smith", "012-34-5678", 120_345.27);
Manager mgr = new Manager(207, "Barbara Johnson", "054-12-2367", 109_501.36, "US Marketing");
Admin adm = new Admin(304, "Bill Munroe", "108-23-6509", 75_002.34);
Director dir = new Director(12, "Susan Wheeler", "099-45-2340", 120_567.36, "Global Marketing", 1_000_000.00);
// Print information about the objects you created
printEmployee(eng);
printEmployee(adm);
printEmployee(mgr);
printEmployee(mgr1);
printEmployee(dir);
System.out.println("\nTesting raiseSalary and setName on Manager:");
mgr.setName ("Barbara Johnson-Smythe");
mgr.raiseSalary(10_000.00);
printEmployee(mgr);
}
public static void printEmployee(Employee emp) {
System.out.println(); // Print a blank line as a separator
// Print out the data in this Employee object
System.out.println("Employee id: " + emp.getEmpId());
System.out.println("Employee name: " + emp.getName());
System.out.println("Employee Soc Sec #: " + emp.getSsn());
System.out.println("Employee salary: " + NumberFormat.getCurrencyInstance().format((double) emp.getSalary()));
}
}
How can I edit according to the given question
Manager.java
package com.example.domain;
public class Manager extends Employee {
private String deptName;
public Manager(int empId, String name, String ssn, double salary, String deptName) {
super(empId, name, ssn, salary);
this.deptName = deptName;
}
public String getDeptName() {
return deptName;
}
}
You can just add an array as follows:
public class Manager extends Employee {
private String deptName;
private List<Employee> employees = new ArrayList<Employee>();
public void addEmployee(Employee someone){
employees.add(someone);
}
and then in your main code, just add them.
manager.addEmployee(someone);
Here is an example using an ArrayList instead of an Array. ArrayLists are good for situations like this, as they are dynamic (you don't have to set a specific size) and they have built in functions for adding and removing without having to shift all of the existing employees up or down the line.
package com.example.domain;
public class Manager extends Employee {
private String deptName;
ArrayList<Employee> employees = new ArrayList<Employee>();
public Manager(int empId, String name, String ssn, double salary, String deptName) {
super(empId, name, ssn, salary);
this.deptName = deptName;
}
public String getDeptName() {
return deptName;
}
public void add(Employee e) {
employees.add(e);
}
public void remove(Employee e) {
employees.remove(e);
}
Use the ArrayList to have the list of Employee object. And it is good practice to have the null check before add an object to the list.
package com.test;
import java.util.ArrayList;
import java.util.List;
public class Manager extends Employee {
private String deptName;
private List<Employee> empList = new ArrayList<Employee>();
public Manager(int empId, String name, String ssn, double salary,
String deptName) {
super(empId, name, ssn, salary);
this.deptName = deptName;
}
public String getDeptName() {
return deptName;
}
public void addEmployee(Employee employee) {
if (employee != null) {
empList.add(employee);
}
}
public boolean removeEmployee(Employee employee) {
return empList.remove(employee);
}
}
It looks like you have your manager class. You could create an ArrayList to store of type Employee and use code such as below to remove it. Alternatively from an int to remove it you could use the ID, Name, or other variations. Hopefully this is somewhat helpful to you or can get you going in the right direction.
` public void removeEmployee(Employee emp, int position) {
this.empArray.remove(position);
System.out.println("Employee was deleted.");
}`
public void addEmployee(Employee emp) {
this.empArray.add(emp);
System.out.println("Employee was Added.");
}
Use arrayList of Employees
ArrayList<Employee> employees = new ArrayList<Employee>();
empolyees.add(employee);

How to print setSalary()?

I want to print how much my salary increase.
Employee class:
public class Employee {
public void setSalary(double i) {
this.salario = i;
}
public double getSalary() {
return this.salario;
}
private double salary;
}
TestEmployee class:
public class TestEmployee {
public static void main(String[] args){
Employee e1 = new Employee();
e1.setEmployee(100);
System.out.println("My salary increase by " + e1.setSalary());
}
}
You should never print a setMethod();
set are void (doesn't return nothing), and they are there to change the values. Whenever printing you must call the getMethod();
That being said you are also confused with terminology and with the language as you mixed Salary and salario a few times.
Employee:
public class Employee {
private double salary;
public void setSalary(double i) {
this.salary = i;
}
public double getSalary() {
return this.salary;
}
}
TestEmployee:
public class TestEmployee {
public static void main(String[] args){
Employee e1 = new Employee();
e1.setSalary(100.00);
System.out.println("My salary was set to " + e1.getSalary());
}
}
Note that you have to SET the salary that is an attribute of the employee, and not the employee.
If you want to increase the value you can do:
setSalary(getSalary()+ 50.00);
Mixing English with your language is not a good idea when coding/posting. Always, when you are trying to post here, make sure you translate your entire code.
You could do something like this.
public class Employee {
private BigDecimal salary;
private BigDecimal latestChangeInSalary;
public Employee(BigDecimal salary) {
this.salary = salary;
latestChangeInSalary = BigDecimal.ZERO;
}
public void setSalary(BigDecimal salary) {
if ( ! salary.equals(this.salary)) {
latestChangeInSalary = salary.subtract(this.salary);
}
this.salary = salary;
}
public BigDecimal getSalary() {
return salary;
}
public BigDecimal getLatestChangeInSalary() {
return latestChangeInSalary;
}
}

How to create a roster of students in java

I have a homework assignment problem that looks like this:
(20 pts) Create a Student class with the following:
A private String variable named “name” to store the student’s name
A private integer variable named “UFID” that contains the unique ID number for this student
A private String variable named “DOB” to store the student’s date of birth
A private integer class variable named numberOfStudents that keeps track of the number of students that have been created so far
A public constructor Student(String name, int UFID, String dob)
Several public get/set methods for all the properties
getName/setName
getUFID/setUFID
getDob/setDob
Write a test program, roster.java, that keeps a list of current enrolled students. It should have methods to be able to enroll a new
student and drop an existing student.
I'm not asking anyone to do this assignment for me, I just really need some general guidance. I think I have the Student class pretty well made, but I can't tell exactly what the addStudent() and dropStudent() methods should do - should it add an element to an array or something or just increments the number of students? The code I have so far looks like this.
public class Student {
private String name;
private int UFID;
private String DOB;
private static int numberOfStudents;
public Student(String name, int UFID, String DOB) {
this.name = name;
this.UFID = UFID;
this.DOB = DOB;
}
public String getDOB() {
return DOB;
}
public void setDOB(String dOB) {
DOB = dOB;
}
public int getUFID() {
return UFID; }
public void setUFID(int uFID) {
UFID = uFID; }
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNumberOfStudents() {
return numberOfStudents;
}
public void setNumberOfStudents(int numberOfStudents) {
Student.numberOfStudents = numberOfStudents;
}
public static void addStudent(String name, int UFID, String DOB) {
numberOfStudents++;
}
public static void dropStudent(String name) {
numberOfStudents--;
}
}
Any guidance as I finish this up would be greatly appreciated.
The assignment writes itself: you need a Roster class that owns and maintains a collection of Students:
public class Roster {
private Set<Student> roster = new HashSet<Student>();
public void addStudent(Student s) { this.roster.add(s); }
public void removeStudent(Student s) { this.roster.remove(s); }
}

Categories