Im currently learning java and im trying to create an Employee management program that stores employee records into an array and allow management to manipulate the array and print any employee reports. So I create a menu and ten employee objects which got stored in an array...now what I want to do is allow the user to input employee details through the menu and that information will be stored inside the objects and I want the user to be able to search for an employee by their title and also display only male of female employees.
I first started with my employee class where has my modifers
public class Employee{
int emp_id=0;
String fname="pebbles";
String lname=null;
String dob=null;
String gender=null;
String address=null;
String title=null;
String dateHired=null;
String department=null;
int hoursWorked=0;
double rateOfpay=0.0;
int leaveDays=0;
double carAllowance=0.0;
double monthlyGratuity=0.0;
double taxRate=0.0;
public Employee(){}
public Employee(int emp_id,String fname,String lname,String dob,String gender,String address,String title,String dateHired,String
department,int hoursWorked,double rateOfpay,int leaveDays,double carAllowance,double monthlyGratuity,double taxRate){
this.emp_id=emp_id;
this.fname=fname;
this.lname=lname;
this.dob=dob;
this.gender=gender;
this.address=address;
this.title=title;
this.dateHired=dateHired;
this.department=department;
this.hoursWorked=hoursWorked;
this.rateOfpay=rateOfpay;
this.leaveDays=leaveDays;
this.carAllowance=carAllowance;
this.monthlyGratuity=monthlyGratuity;
this.taxRate=taxRate;
}
public Employee(int emp_id,String fname,String lname){
this.emp_id=emp_id;
this.fname=fname;
this.lname=lname;
}
public void setEmployeeId(int emp_id){
this.emp_id=emp_id;
}
public void setFirstName(String fname){
this.fname=fname;
}
public void setLastName(String lname){
this.lname=lname;
}
public void setDateOfBirth(String dob){
this.dob=dob;
}
public void setGender(String gender){
this.gender=gender;
}
public void setAddress(String address){
this.address=address;
}
public void setTitle(String title){
this.title=title;
}
public void setDateHired(String dateHired){
this.dateHired=dateHired;
}
public void setDepartment(String department){
this.department=department;
}
public void setHoursWorked(int hoursWorked){
this.hoursWorked=hoursWorked;
}
public void setRateOfPay(double rateOfpay){
this.rateOfpay=rateOfpay;
}
public void setLeaveDays(int leaveDays){
this.leaveDays=leaveDays;
}
public void setCarAllowance(double carAllowance){
this.carAllowance=carAllowance;
}
public void setMonthlyGratuity(double monthlyGratuity){
this.monthlyGratuity=monthlyGratuity;
}
public void setTaxRate(double taxRate){
this.taxRate=taxRate;
}
public int getEmployeeId(){
return emp_id;
}
public String getFirstName(){
return fname;
}
public String getLastName(){
return lname;
}
public String getDateOfBirth(){
return dob;
}
public String getGender(){
return gender;
}
public String getAddress(){
return address;
}
public String getTitle(){
return title;
}
public String getDateHired(){
return dateHired;
}
public String getDepartment(){
return department;
}
public int getHoursWorked(){
return hoursWorked;
}
public double getRateOfPay(){
return rateOfpay;
}
public int getLeaveDays(){
return leaveDays;
}
public double getCarAllowance(){
return carAllowance;
}
public double getMonthlyGratuity(){
return monthlyGratuity;
}
public double getTaxRate(){
return taxRate;
}
}
Then created the objects and arrays in the class below
import java.util.Scanner;
public class employeeArray extends Employee{
private static Employee employees[] = new Employee[10];
static Scanner input=null;
String fname="pebbles";
String lname=null;
String dob=null;
String gender=null;
int emp_id=0;
String address=null;
String title=null;
String dateHired=null;
String department=null;
int hoursWorked=0;
double rateOfpay=0.0;
int leaveDays=0;
double carAllowance=0.0;
double monthlyGratuity=0.0;
double taxRate=0.0;
public static Employee e1=new Employee(12345,"Aobakwe","Mothabi","26/07/1990","Male","Private 009 Masunga","CEO",
"06/02/2008","Finance",500,50.0,10,100.0,1500,5.1);
public static Employee e2=new Employee();
public static Employee e3=new Employee();
public static Employee e4=new Employee();
public static Employee e5=new Employee();
public static Employee e6=new Employee();
public static Employee e7=new Employee();
public static Employee e8=new Employee();
public static Employee e9=new Employee();
public static Employee e10=new Employee();
public static void main(String args[]){
input=new Scanner(System.in);
Employee e1=new Employee(12345," ","Mothabi","26/07/1990","Male","Private 009 Masunga","CEO",
"06/02/2008","Finance",500,50.0,10,100.0,1500,5.1);
Employee e2=new Employee();
Employee e3=new Employee();
Employee e4=new Employee();
Employee e5=new Employee();
Employee e6=new Employee();
Employee e7=new Employee();
Employee e8=new Employee();
Employee e9=new Employee();
Employee e10=new Employee();
employees[0]=e1;
employees[1]=e2;
employees[2]=e3;
employees[3]=e4;
employees[4]=e5;
employees[5]=e6;
employees[6]=e7;
employees[7]=e8;
employees[8]=e9;
employees[9]=e10;
//ENTER NAME
System.out.println("Enter name");
String fname=input.next();
e2.setFirstName(fname);
//ENTER LAST NAME
System.out.println("Enter surname");
String lname=input.next();
e2.setLastName(lname);
//ENTER DATE OF BIRTH
System.out.println("Enter date of birth");
String dob=input.next();
e2.setDateOfBirth(dob);
//ENTER GENDER
System.out.println("Enter Gender");
String gender=input.next();
e2.setGender(gender);
//ENTER EMPLOYEE ID
System.out.println("Enter Employee Id");
int emp_id=input.nextInt();
e2.setEmployeeId(emp_id);
//ENTER ADDRESS
System.out.println("Enter Address");
String address=input.next();
e2.setAddress(address);
//ENTER TITLE
System.out.println("Enter Employee Title");
String title=input.next();
e2.setTitle(title);
//ENTER DATE HIRED
System.out.println("Enter Date Hired");
String dateHired=input.next();
e2.setDateHired(dateHired);
//ENTER DEPARTMENT
System.out.println("Enter Department");
String department=input.next();
e2.setDepartment(department);
//ENTER HOURS WORKED
System.out.println("Enter Hours Worked");
int hoursWorked=input.nextInt();
e2.setHoursWorked(hoursWorked);
//ENTER RATE OF PAY
System.out.println("Enter Rate Of Pay");
double rateOfpay=input.nextDouble();
e2.setRateOfPay(rateOfpay);
//ENTER LEAVE DAYS
System.out.println("Enter Leave Days");
int leaveDays=input.nextInt();
e2.setLeaveDays(leaveDays);
//ENTER CAR ALLOWANCE
System.out.println("Enter Car Allowance");
double carAllowance=input.nextDouble();
e2.setCarAllowance(carAllowance);
//ENTER MONTHLY GRATUITY
System.out.println("Enter Monthly Gratuity");
double monthlyGratuity=input.nextDouble();
e2.setMonthlyGratuity(monthlyGratuity);
//ENTER TAX RATE
System.out.println("Enter Tax Rate");
double taxRate=input.nextDouble();
e2.setTaxRate(taxRate);
//DISPLAY RESULTS
System.out.println(e2.getFirstName());
System.out.println(e2.getLastName());
System.out.println(e2.getDateOfBirth());
System.out.println(e2.getGender());
System.out.println(e2.getEmployeeId());
System.out.println(e2.getAddress());
System.out.println(e2.getTitle());
System.out.println(e2.getDateHired());
System.out.println(e2.getDepartment());
System.out.println(e2.getHoursWorked());
System.out.println(e2.getRateOfPay());
System.out.println(e2.getLeaveDays());
System.out.println(e2.getCarAllowance());
System.out.println(e2.getMonthlyGratuity());
System.out.println(e2.getTaxRate());*/
}
static void mainMenu(){
System.out.println(
"Select an option\n"+
"1)Add Employee Records\n"+
"2) display only male of female employees\n"+
"3) display all employees and their gross salaries\n"+
"4) search for an employee and display salary calculated.\n");
}
}
and lastly here is my tester class which displays the menu and allows the user to select an option
import java.util.Scanner;
public class empTester extends employeeArray{
static Scanner input=null;
public static void main(String args[]){
input=new Scanner(System.in);
mainMenu();
int choice=input.nextInt();
if(choice==1){
menuAdd();
int option=input.nextInt();
if(option==1){EmployeeCreation();}
else if(option==2){System.out.println("It works number 2");}
else if(option==3){mainMenu();}
}
else if(choice==2){
menuDisplay();
int option=input.nextInt();
if(option==1){System.out.println("It works number 1");}
else if(option==2){System.out.println("It works number 2");}
else if(option==3){System.out.println("It works number 3");}
else if(option==4){System.out.println("It works number 4");}
else if(option==5){mainMenu();}
}
else if(choice==3){
menuSearch();
int option=input.nextInt();
if(option==1){System.out.println("It works number 1");}
else if(option==2){System.out.println("It works number 2");}
else if(option==3){mainMenu();}
}
else if(choice==4){
System.out.println("This is the About Section");
}
else if(choice==5){
System.out.println("Ending Program");
System.exit(0);
}
}
}
Yeah so I managed to find a way to enable the user to add an employee record and display details added. Im having trouble creating methods for other functions stated in the menu without having to create new objects.
I think you need a static list.
public static List<Employee> employees = new ArrayList<>();`
public void addEmployee() {
Employee employee = new Employee();
input=new Scanner(System.in);
String fname=input.next();
employee.setFirstName(fname);
.
.
. and others setters...
eployees.add(employee);
}
And read about toString() method to display object details.
toString(), ArrayList, static variable
Here are a few suggestions. The Employee class seems ok. Note that you do not need to supply default values for variables if they are the same as the type's default value. Ex:
String lname=null;
int hoursWorked=0;
double rateOfpay=0.0;
Is the same as
String lname;
int hoursWorked;
double rateOfpay;
You might consider adding a function to the class to read data from a Scanner:
class Employee {
....
boolean readFromIn(Scanner input)
{
//ENTER NAME
System.out.println("Enter name");
fname = input.next();
//ENTER LAST NAME
System.out.println("Enter surname");
lname = input.next();
etc....
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(lname);
....fill in rest
return sb.toString();
}
....
}
The entire employeeArray class seems necessary. But if you want that, there's no need for the temporary variables e1, e2, etc. You have the array, you can add directly to it. A loop helps here:
public class EmployeeArray /* extends Employee - does not extend Employee */
{
private static Employee employees[] = new Employee[10]; // why static?
public static void createEmployees()
{
Scanner in = new Scanner(System.in);
for (int i = 0; i < employees.length; i++) {
employees[i] = new Employee();
employees[i].readFromIn(in);
}
}
public static Employee getEmployee(int index)
{
if (index < 0 || index >= employees.length) {
throw new ArrayIndexOutOfBoundsException();
}
return employees[i];
}
}
Related
i really need help with my program. I'm new to Arraylist and I have no idea how can i search and display an object by its ID number.
So the program has 4 class: Main, Person (parent class) Student and Employee (both are child of Person)
Now my main class has a menu that will do the following:
Add Student ( ID must be unique for each stud )
Add Employee ( ID must be unique for each emp )
Search Student ( By Student ID then display it)
Search Employee ( By Employee No then display it)
Display All ( Display All Stud and Employee )
Quit
I have done this before with array searching and displaying but now we have to use Arraylist which is better but im new to it.
Any help and suggestion is highly appreciated. Thank you!
Here's my code:
Main Class:
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args){
ArrayList<Student> stud = new ArrayList<Student>();
ArrayList<Employee> emp = new ArrayList<Employee>();
while (true) {
int select;
System.out.println("Menu");
System.out.println("1. Add Student");
System.out.println("2. Add Employee");
System.out.println("3. Search Student");
System.out.println("4. Search Employee");
System.out.println("5. Display All");
System.out.println("6. Quit");
select = sc.nextInt();
switch (select) {
case 1:
addStud(stud);
break;
case 2:
addEmp(emp);
break;
case 3:
srchStud();
break;
case 4:
srchEmp();
case 5:
displayAll(stud, emp);
break;
case 6:
return;
default:
System.out.println("Invalid Option");
}
}
}
public static void addStud(ArrayList<Student> stud) {
String name, address, course;
int age, cNum, studNum, year;
int addMore;
System.out.println("ADD STUDENT");
do {
System.out.println("Student No: ");
studNum = sc.nextInt();
sc.nextLine();
for(int x = 0; x < stud.size(); x++){ // Please help fix, this accepts another ID if already existing to prevent duplicate
if(studNum == stud[x].getStudNum()) { // this code works with array of object but not on arraylist,
System.out.println("The Student ID: " +studNum+ " already exist.\nEnter New Student ID: ");
studNum = sc.nextInt();
sc.nextLine();
x = -1;
}
}
System.out.println("Name: ");
name = sc.nextLine();
System.out.println("Age: ");
age = sc.nextInt();
sc.nextLine();
System.out.println("Address: ");
address = sc.nextLine();
System.out.println("Contact No: ");
cNum = sc.nextInt();
sc.nextLine();
System.out.println("Course: ");
course = sc.nextLine();
System.out.println("Year: ");
year = sc.nextInt();
sc.nextLine();
stud.add(new Student(name, address, age, cNum, studNum, year, course));
System.out.println("To add another Student Record Press 1 [any] number to stop");
addMore = sc.nextInt();
sc.nextLine();
} while (addMore == 1);
}
public static void addEmp(ArrayList<Employee> emp) {
String name, address, position;
int age, cNum, empNum;
double salary;
int addMore;
System.out.println("ADD Employee");
do {
System.out.println("Employee No: ");
empNum = sc.nextInt();
sc.nextLine();
for(int x = 0; x < emp.size(); x++){
if(empNum == emp[x].getEmpNum()) {
System.out.println("The Employee ID: " +empNum+ " already exist.\nEnter New Student ID: ");
empNum = sc.nextInt();
sc.nextLine();
x = -1;
}
}
System.out.println("Name: ");
name = sc.nextLine();
System.out.println("Age: ");
age = sc.nextInt();
sc.nextLine();
System.out.println("Address: ");
address = sc.nextLine();
System.out.println("Contact No: ");
cNum = sc.nextInt();
sc.nextLine();
System.out.println("Position: ");
position = sc.nextLine();
System.out.println("Salary: ");
salary = sc.nextInt();
sc.nextLine();
emp.add(new Employee(name, address, age, cNum, empNum, salary, position));
System.out.println("To add another Student Record Press 1 [any] number to stop");
addMore = sc.nextInt();
sc.nextLine();
} while (addMore == 1);
}
public static void displayAll(ArrayList<Student> stud, ArrayList<Employee> emp){ // Definitely not working with Arraylist
System.out.println("Student ID\tStudent Name\tStudent Course\tStudent Year");
for (int x = 0; x < stud.size(); x++) {
System.out.println(stud[x].getStudNum() + "\t\t\t\t" + stud[x].getName() + "\t\t\t\t" + stud[x].getCourse() + "\t\t\t\t" + stud[x].getYear());
}
}
}
Person Class :
public class Person {
private String name, address;
private int age, cNum;
public Person() {
}
public Person(String name, String address, int age, int cNum) {
this.name = name;
this.address = address;
this.age = age;
this.cNum = cNum;
}
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 getcNum() {
return cNum;
}
public void setcNum(int cNum) {
this.cNum = cNum;
}
}
Student Class :
public class Student extends Person{
private int studNum, year;
private String course;
public Student(String name, String address, int age, int cNum, int studNum, int year, String course) {
super(name, address, age, cNum);
this.studNum = studNum;
this.year = year;
this.course = course;
}
public int getStudNum() {
return studNum;
}
public void setStudNum(int studNum) {
this.studNum = studNum;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
}
Employee Class :
public class Employee extends Person {
private int empNum;
private double salary;
private String position;
public Employee(String name, String address, int age, int cNum, int empNum, double salary, String position) {
super(name, address, age, cNum);
this.empNum = empNum;
this.salary = salary;
this.position = position;
}
public int getEmpNum() {
return empNum;
}
public void setEmpNum(int empNum) {
this.empNum = empNum;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
}
If you are not limited to use ArrayList, better performance will be achieved using a Map.
Map<Integer, Employee> employeeIndex = new HashMap<>();
//put
employeeIndex.put(employeeId, empployee);
//get
employeeIndex.get(employeeId);
In case, you need to use ArrayList, you can use filter:
List<Student> students = new ArrayList<Student>();
List<Student> filteredStudent = students.stream()
.filter(student -> student.getStudNum() == student_id)
.collect(Collectors.toList());
just this way if you are searching for a student the id is 12
ArrayList<Integer> students;
students.forEach(stu -> {if ( stu.getStudNum() == 2) System.out.println(stu.getName());});
I have written the code this expected output:
Sample input :
Enter the passenger name:
Priya
Enter the gender(M or F / m or f):
F
Enter the age:
61
Enter the ticket no:
140
Enter the ticket price:
500.0
Sample Output 1 :
Ticket no:143
Passenger Name:Priya
Price of a ticket : 500.0
Total Amount : 375.0
I have to change the total amount value based on the age and gender for which I have written function.
My code:
Person.java
public class Person {
private String name;
private char gender;
private int age;
public void setName(String name ){
this.name = name;
}
public void setGender(char gender){
this.gender = gender ;
}
public void setAge(int age ){
this.age = age;
}
public String getName(){
return this.name;
}
public char getGender(){
return this.gender;
}
public int getAge(){
return this.age;
}
}
BusTicket.java
public class BusTicket {
private int ticketNo;
private float ticketPrice;
private float totalAmount;
Person person = new Person();
int age = person.getAge();
char g = person.getGender();
public void setTicketNo(int ticketNo){
this.ticketNo = ticketNo;
}
public void setTicketPrice(float ticketPrice){
this.ticketPrice = ticketPrice;
}
public void setTotalAmount(float totalAmount){
this.totalAmount = totalAmount;
}
public void calculateTotal()
{
if(age<16)
{
totalAmount = ticketPrice/2;
setTotalAmount(totalAmount);
}
else if(age>=60)
{
totalAmount = 3*(ticketPrice/4);
setTotalAmount(totalAmount);
}
else if(g == 'f'|| g== 'F')
{
totalAmount = 9*(ticketPrice/10);
setTotalAmount(totalAmount);
}
else{
setTotalAmount(ticketPrice);
}
}
public int getTicketNo(){
return this.ticketNo;
}
public float getTicketPrice(){
return this.ticketPrice;
}
public float getTotalAmount(){
return this.totalAmount;
}
}
TestMain.java
import java.util.Scanner;
public class TestMain {
public static BusTicket getTicketDetails()
{
Scanner sc = new Scanner(System.in);
BusTicket bt = new BusTicket();
System.out.println("Enter the ticket no:");
bt.setTicketNo(sc.nextInt());
System.out.println("Enter the ticket price:");
bt.setTicketPrice(sc.nextFloat());
return bt;
}
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
Person p = new Person();
BusTicket bt;
System.out.println("Enter the passenger name:");
p.setName(sc.nextLine());
System.out.println("Enter the gender(M or F/ m or f):");
p.setGender(sc.next().charAt(0));
System.out.println("Enter the age:");
p.setAge(sc.nextInt());
bt = getTicketDetails();
System.out.println("Ticket no:"+bt.getTicketNo());
System.out.println("Passenger Name:"+p.getName());
System.out.println("Price of a ticket : "+bt.getTicketPrice());
System.out.println("Total Amount : "+bt.getTotalAmount());
}
}
But my TotalAmount value is always coming 0.0, it is not getting updated.
And some test cases are failed please help to resolve them:
Fail 1 -
Incorrect access specifier/modifier for person -Should be a [private]
Fail 2 -
Check whether the signature(Returntype/Argument/AccessSpecifier/MethodName) of the method setPerson is correct
Fail 3-
Check whether the signature(Returntype/Argument/AccessSpecifier/MethodName) of the method getPerson is correct
Please Help
Thanks
You need to call calculateTotal to update totalAmount. Otherwise, it will be always 0.0.
...
System.out.println("Price of a ticket : "+bt.getTicketPrice());
bt.calculateTotal(); // Add this line
System.out.println("Total Amount : "+bt.getTotalAmount());
In your BusTicket class a new Person object is assigned to Person attribute and then you are trying to get age and gender details from that newly created Person object, but at this moment Person's age and gender are not populated yet.
Person person = new Person();
int age = person.getAge();
That's why you are getting 0. What should ideally happen is, you should pass the person object created using the input details to the BusTicket class and populate the BusTicket's person attribute with that person.For now I ll tell just that. :)
Give a try :)
In your BusTicket class, create a getter and setter for the Person object, and set the value from the main method.
So, I've got some homework to do and I made a simple user input application that at the end outputs (I want that I do that) all inputs that were typed. The problem is I don't know how to make it that it doesn't overwrite the existing object but that it makes a new one.
I presume that I can make an array or something like that and it should resolve the problem, but it doesn't resolve my question, so I came here for help.
public class Main {
public static void main(String[] args) {
String next ="y";
int studentNum = 1;
Scanner scanner = new Scanner(System.in);
System.out.println("Do you want to add a student? y/n");
if(scanner.nextLine().equalsIgnoreCase("n"))
System.exit(0);
for(int i = 0;i<studentNum;i++){
Student student = new Student();
System.out.println("ID: ");
student.setId(scanner.nextLine());
System.out.println(("Ime: "));
student.setName(scanner.nextLine());
System.out.println("Prezime: ");
student.setSurname(scanner.nextLine());
System.out.println("Do you want to add another student? y/n");
if(scanner.nextLine().equalsIgnoreCase("y"))
studentNum+=1;
else
for(i =0;i<studentNum;i++)
System.out.println(student.toString());
}
}
And the Student Class
public class Student {
#Override
public String toString() {
return String.format("ID: %s \n%s %s\nAverage grade %.2f\n____________________\n",
id, surname, name, averageGrade() );
}
#Override
public boolean equals(Object obj) {
// pretpostavljamo da je predani objekt iz klase Student
Student otherStudent = (Student) obj;
return id.equals(otherStudent.id);
}
final int ARR_SIZE = 60;
private String id;
private String name;
private String surname;
private int noOfGrades;
private CourseGrade[] grades;
public String getId() {
return id;
}
public void setId(String newId) {
id = newId;
}
public String getName() {
return name;
}
public void setName(String newName) {
name = newName;
}
public String getSurname() {
return surname;
}
public void setSurname(String newSurname) {
surname = newSurname;
}
If I want to add another student it overwrites the existing one, which I expected, but I don't know how to make it that it makes a new instance.
Here is example code of how to use a List to store several students:
import java.util.List;
import java.util.ArrayList;
..
List<Student> students = new ArrayList<Student>();
Student s = new Student();
s.setName("Joe");
students.add(s);
Student t = new Student();
t.setName("Jack");
students.add(t);
for(Student student : students) {
System.out.println(student.toString());
}
With this information, you should be able to finish your work.
I have been trying to create a small program that prompts the user for input that takes an employee name and salary adds it to an arrayList, then displays options on the screen(e.g 0: quit, 1: add, 2: display), reads the input then proceeds based on the input.Displaying would just be(e.g Last Name: Smith Salary: £14000. Just need some help to point me in the right direction. I currently have 3 classes Employee, Employee List and Employee Test.
This class prompts the user input.
import java.util.Scanner;
public class Employee {
private String Last_Name;
private int Salary;
public Employee(){
Scanner inputValues = new Scanner(System.in);
System.out.print("Enter employee last name: ");
Last_Name = inputValues.next();
System.out.print("Enter Employee Salary: " + "£");
Salary = inputValues.nextInt();
}
public void Display(){
System.out.printf("Name: " + Last_Name + " " + "Salary: " + Salary);
System.out.println("\n");
}
}
This class is supposed to be adding the employees to an arraylist but im not sure if im doing it correctly.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class EmployeeList extends Employee{
private List <Employee> employee = new ArrayList<Employee>();
public EmployeeList(Employee person) {
employee.add(person);
}
public void DisplayEmployees(){
System.out.println("Employee:" + employee.size());
displayList(employee);
}
public static void displayList(List employee) {
}
}
This is where the main method is
import java.util.Scanner;
public class EmployeeTest {
public static void main(String[] args) {
Employee employee = new Employee();
employee.Display();
EmployeeList empList = new EmployeeList(employee);
empList.DisplayEmployees();
Scanner scanner = new Scanner(System.in);
System.out.println("0: quit, 1: add, 2: display");
String employees = scanner.next();
/* if (employees.equals("1")){
//not sure how to go back to displaying the user prompts
break;
} */
}
}
Few tips I can think of:
EmployeeList should not extend Employee. The main rule of OOP is that class A extends class B if B is a A. This is clearly not the case here - employeeList is not an employee, it's a list of employees (In my mind you don't need a class for this, just List<Employee>)
I'd separate the logic from the data. meaning - Employee class should only hold the employee's data, not deal with scanning and getting the input from the user. the constructor should be simple in my mind, something like:
public Employee(String name, int salary) {
this.name = name;
this.salary = salary;
}
The logic of getting the data should be outside of this class, either in an EmployeeHandler or in the main itself. Since you put it inside the employee, you are having troubles continuing when some of the logic is in the employee and some in the main.
the high-level code should be something like (I'll leave the details to you):
show the menu options to the user
if he wants to add user, get input for both variables, create the employee object and add it to the list
if he wants to display, go over the list and print (the printing can be done overriding toString in Employee class)
if he wants to quit, finish
continue this loop until he wants to quit
public class Employee {
private String Last_Name;
private int Salary;
public Employee(){
public String getLName(){
return Last_Name;
}
public void setLName(){
this.Last_Name = Last_Name;
}
public int getSalary(){
return salary;
}
public void setSalary(){
this.salary = salary;
}
}
}
then in your main method you can create the employee object.
public static void main(String[] args){
Employee employee = new Employee();
Scanner scanner = new Scanner(System.in);
employee.setLName = scanner.next();
employee.setSalary = scanner.nextInt();
}
If i were you I would just make an arraylist to hold all employees. I would prompt the input option for x amount of times and add to the end of the arraylist. the arraylist would be created as so
ArrayList<Employee> employeeList = new ArrayList<Employee>();
to add to it use add
employeeList.add(employee);
This should be able to get you started
EDIT:
OOPS, made several mistakes. edit with the following. Note that it is employee.setLastName(value) because the method setLastName is part of the employee class and it must be passed a value because we have defined that in the employee class.
Employee employee = new Employee();
Scanner scanner = new Scanner(System.in);
String tempName = scanner.next();
int tempSalary = scanner.nextInt();
employee.setLastName(tempName);
employee.setSalary(tempSalary);
EDIT 2:
try to print arraylists as follows. didnt test it. let me know how it works.
for (int i = 0; i< employeelist.size(); i++){
Employee temp = values.get(i);
System.out.println("Last Name: " + temp.getLname() + "Salary: " + temp.getSalary());
}
I modified my employee class to look like this:
public class Employee {
public String lastName;
private int salary;
public Employee(){
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
#Override
public String toString(){
return "Employee Last Name: " + lastName + "\n" + "Employee Salary: " + salary;
}
}
I have modified my EmployeeTest class:
This is my EmployeeTest class:
import java.util.ArrayList;
import java.util.Scanner;
public class EmployeeTest {
static ArrayList<Employee> employeeList = new ArrayList<Employee>();
public static void main(String[] args) {
for(int i=0;i<5;i++){
addEmployees(employeeList);
}
System.out.println(employeeList.toArray());
}
public static void addEmployees(ArrayList<Employee> employeeList){
Scanner scanner = new Scanner(System.in);
System.out.println("0: quit, 1: add, 2: display");
String options = scanner.next();
if(options.equals("1")){
System.out.print("Enter employee last name: ");
String lastname = scanner.next();
System.out.print("Enter Employee Salary: " + "£");
int salary = scanner.nextInt();
Employee employee = new Employee();
EmployeeList.add(employee);
}
else if(options.equals("2")){
for (Employee employee : employeeList){
/*System.out.println("Name: " + employee.getLastName() + ", " + "Salary: " + employee.getSalary());*/
System.out.println(employee);
}
}
else{
System.exit(0);
}
}
}
However when i press 2 as my options it doesn't display what is in my arraylist.
I had read that a toString method is used to get those details so i could print them to the screen. And that using this for loop gets each item in the list to display them. Am i missing something here?. Apologies for this dragging on a bit, im just wanting this to work.
When I try to print a collection object, it prints Employee#122392Iie92. Why is it printing this and not the details of the employee list?
My code:
public class Employee {
private String name;
private String designation;
private int employeeId;
private int salary;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public int getEmployeeId() {
return employeeId;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}
import java.util.ArrayList;
import java.util.Scanner;
public class EmployeeManagement {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList <Employee> lst = new ArrayList <Employee> ();
System.out.println("Enter the number of employees : ");
int num = sc.nextInt();
EmployeeManagement emp = new EmployeeManagement();
emp.addEmployeeName( num, lst);
}
public void addEmployeeName(int num,ArrayList<Employee> lst) {
Employee em = new Employee();
for(int i =0; i<num ; i++)
{
System.out.println("Enter the employee id : ");
em.setEmployeeId(sc.nextInt());
System.out.println("Enter the name of employee : ");
em.setName(sc.next());
System.out.println("Enter the designation of employee : ");
em.setDesignation(sc.next());
System.out.println("Enter the Salary of employees : ");
em.setSalary(sc.nextInt());
lst.add(em);
}
System.out.println(lst);
}
}
It is printing using the default toString method of the Object class. You need to override toString in the Employee class if you want to show values. It is currently showing the class name and hashcode.
Write a toString method like this in Employee:
#Override
public String toString(){
SubString sb = new SubString();
sb.append("Name :- ")append(name).append(id); //all relevant fields
return sb.toString();
}
Move new statement inside loop else you are adding and updating same object again and again.
public void addEmployeeName(int num,ArrayList<Employee> lst) {
for(int i =0; i<num ; i++)
{
Employee em = new Employee();
System.out.println("Enter the employee id : ");
em.setEmployeeId(sc.nextInt());
System.out.println("Enter the name of employee : ");
em.setName(sc.next());
System.out.println("Enter the designation of employee : ");
em.setDesignation(sc.next());
System.out.println("Enter the Salary of employees : ");
em.setSalary(sc.nextInt());
lst.add(em);
}
System.out.println(lst);
}
}