I have a class look like this:
public class People {
private String Name;
private String Address;
public People(String aName, String aAddress) {
this.Name=aName;
this.Address=aAddress;
}
public String getName() {
return Name;
}
public String getAddress() {
return Address;
}
void display() {
System.out.println("Name:\t"+Name);
System.out.println("Address:\t" +Address);
}
}
and another 2:
class Students extends People{
private int MatriculationNumber;
private String CourseName;
public Students (String aName, String aAddress, int matriculationNumber, String courseName){
super(aName,aAddress);
this.MatriculationNumber=matriculationNumber;
this.CourseName=courseName;
}
void display() {
super.display();
System.out.println("Matriculation Number: \t" +MatriculationNumber);
System.out.println("Course Name: \t" +CourseName);
}
}
class Staffs extends People{
private int EmployeeNumber;
private String Department;
public Staffs (String aName, String aAddress, int employeeNumber, String department){
super(aName,aAddress);
this.EmployeeNumber=employeeNumber;
this.Department=department;
}
void display() {
super.display();
System.out.println("Employee Number: \t" +EmployeeNumber);
System.out.println("Department: \t" +Department);
}
}
The question is how to create a class named "School" which have a List can contain both Students and Staffs, so I can add a method like AddPeople() which can add or remove Students or Staffs from it?
You can use the below solution. The solution is not thread-safe but should work fine for your usecase.
import java.util.ArrayList;
class School {
private List<People> peopleList = new ArrayList<People>();
public void addPeople(People people) {
peopleList.add(people);
}
public void removePeople(People people) {
peopleList.remove(people);
}
public static void main(String... args) {
Student student = new Student("Name", "Address", 90, "Course");
Staff staff = new Staff("Name", "Address", 1001, "Department");
School school = new School();
school.addPeople(student);
school.addPeople(staff);
school.removePeople(student);
school.removePeople(staff);
}
}
You can create a new Staff Class which also extends from the People Class
package so;
public class Staff extends People {
public Staff(String aName,String aAddress) {
super(aName, aAddress);
}
}
Then give as type of your list the base class People.
package so;
import java.util.ArrayList;
import java.util.List;
public class School {
List<People> peopleContainer = new ArrayList<People>();
public void addPeople(People p){
this.peopleContainer.add(p);
}
public void removePeople(People p) {
this.peopleContainer.remove(p);
}
public void displayPeople() {
for(People person : peopleContainer) {
person.display();
}
}
}
Then you can add staff and student objects to your list and also all other objects which classes extends from people or even people objects itself.
package so;
public class Main {
public static void main(String[] args) {
Students stud1 = new Students("Max", "MustermanAddress", 181242, "CS50");
Staff staff1 = new Staff("Christian", "AugustAddress");
School school = new School();
school.addPeople(stud1);
school.addPeople(staff1);
school.displayPeople();
school.removePeople(staff1);
System.out.println();
System.out.println();
school.displayPeople();
}
}
Output will be
Name: Max
Address: MustermanAddress
Matriculation Number: 181242
Course Name: CS50
Name: Christian
Address: AugustAddress
Name: Max
Address: MustermanAddress
Matriculation Number: 181242
Course Name: CS50
Related
I have this exercise and the question is how can I solve the error "grade" cannot be resolved to a variable, without declare it in the class teacher. I suppose is the only error in my code. It is evident for me WHY then in my output only the grade variable is not assigned, but I don't know HOW to solve it.
public class App {
public static void main(String[] args) throws Exception {
Student studentOne = new Student("FraPedu");
Student studentTwo = new Student("FraIla");
Teacher teacherOne = new Teacher();
teacherOne.teacherName = "Tiziana";
teacherOne.assignGrade(studentOne,10);
teacherOne.assignGrade(studentTwo,10);
studentOne.getStudentDetails();
studentTwo.getStudentDetails();
}
}
public class Student {
public String name;
public int grade;
public Student(String studentName) {
System.out.println("Student object has been created succesfully!");
name = studentName;
}
public void getStudentDetails() {
System.out.println("Student name and grade: " + name + " " + grade);
}
}
public class Teacher {
public String teacherName;
public Teacher() {
System.out.println("Teacher object has been created succesfully!");
}
public void assignGrade(Student alum, int finalGrade) {
grade = finalGrade;
}
}
You need to assign the grade to the Student object you are passing to the assignGrade method.
public class Teacher {
public String teacherName;
public Teacher() {
System.out.println("Teacher object has been created succesfully!");
}
public void assignGrade(Student alum, int finalGrade) {
alum.grade = finalGrade; // << this is the line I changed
}
}
Person.java
package A;
public class Person {
public String name , surname;
public Person() {
name = " Unknown ";
surname = " Unknown ";
}
public Person(String n , String s) {
name = n;
surname = s;
}
public Person(Person p1) {
name = p1.name;
surname = p1.surname;
}
}
ContactInfo.java
package A.B;
import A.Person;
public class ContactInfo extends Person {
public String phone;
public ContactInfo() {
phone = "Unvalid ";
}
public ContactInfo(String n , String s , String phn) {
super(n,s);
phone = phn;
}
public ContactInfo(ContactInfo ci) {
super(ci);
phone = ci.phone;
}
}
Employee.java
package A.B.C;
import A.B.ContactInfo;
public class Employee extends ContactInfo {
int salary;
public Employee() {
salary = 0;
}
public Employee(String n , String s , String phn ,int sal) {
super(n,s,phn);
salary = sal;
}
public Employee(Employee e) {
super(e);
salary = e.salary;
}
public void show() {
System.out.println("Name: "+name+surname+ " Phone: "+phone+ " Salary: "+salary);
}
}
Office.java
//import A.B.C.Employee;
import A.B.C.*;
class Office {
public static void main(String args[]) {
Employee e1 = new Employee();
System.out.println();
e1.show();
Employee e2 = new Employee(" John "," Snow "," 001122 ",123);
System.out.println();
e2.show();
Employee e3 = new Employee(e2);
System.out.println();
e3.show();
}
}
As in Office.java file when i using this statment : import A.B.C.Employee;
it will shows the desired output but when i using : import
A.B.C.*; it will shows errors. Why it is always fails to get the correct path?
Little help is needed to understand it .
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);
}
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);
I finished all the classes except for the student class. I don't understand how to approach it. Here is the prompt.
Extend the Person class developed in
lab1 to derive classes for students,
hourly employees, and full-time
salaried employees. Determine an
appropriate class inheritance
hierarchy. These classes should have
the following fields, necessary
constructors, and appropriate access
and modifier methods.
for all employees:
*department
full-time employees:
*salary
hourly employees:
*hourly rate
*number of hours worked each week(4weeks)
the hourly employee class should
contain the necessary methods that
will print the total hours (four- week
total), average hours per week worked
by each employee, and the total wages
during a four-week period.
student:
*classes taken and grades for each class (use an ArrayList)
The student class should contain the
necessary methods to print the
transcript for each student
(write a tester class to test your
classes)
How should I use an arraylist for the student class?
I'm only going to post the relevant classes
public class Person { private String first; private String last; private static int idNumber = 1001; int Id ; private String full;
Person(){
}
Person(String fn,String ln){
first = fn;
last = ln;
Id = idNumber++;
full = first +" "+ last;
}
static int getidNumber(){
return idNumber;
}
void setfirst(String fn) {
first = fn;
}
String getfirst(){
return first; }
void setlast(String ln){
last = ln; }
String getlast(){
return last; }
#Override
public String toString(){
String blah = "First name: " +first+ " Last Name:" +last+ "\tThe full name is: "+full+" Id#"+Id;
return blah;
}
}
import java.util.*;
public class Student extends Person{
Student (String fn, String ln){
super(fn,ln);
}
}
Thank you in advance for all advices and suggestions.
I would use a map here, but since an ArrayList is required, I would do something like that:
public class Student extends Person {
private List<ClassGrade> classes = new ArrayList<ClassGrade>();
public List<ClassGrade> getClassGrades() {
return new ArrayList<ClassGrade>(classes);
}
public void addClass(String clazz, int grade) {
classes.add(new ClassGrade(clazz, grade));
}
public static class ClassGrade {
String clazz;
int grade;
public ClassGrade(String clazz, int grade) {
this.clazz = clazz;
this.grade = grade;
}
public String getClazz() {
return clazz;
}
public int getGrade() {
return grade;
}
}
}
import static java.lang.System.*;
class Student extends Person
{
protected int avMark;
String classTaken
public Student()
{
}
public Student(String nameInput, int ageInput, String class)
{
super(nameInput, ageInput);
classTaken = class;
}
public void setClasTaken(String className){
classTaken = classname;
}
public String setClasTaken(){
return classTaken;
}
public void register()
{
super.register();
out.println("Classes taken " +classTaken
out.println("Average mark is " + avMark);
}
}
here is something to start you off
this class inherits everything from the person class.