Edit Method for Hashmap EmployeeStore - java

I am making an EmployeeStore that will store names, dob, id, email address etc... and i need to write an edit method. I have googled and i cannot find how to do this can anyone help? Here is my code:
//Imports.
import java.util.Scanner;
//********************************************************************
public class MainApp
{
private static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args)
{
new MainApp().start();
}
public void start()
{
EmployeeStore Store = new EmployeeStore();
Store.add(new Employee ("James O' Carroll", 18,"hotmail.com"));
Store.add(new Employee ("Andy Carroll", 1171,"yahoo.com"));
Store.add(new Employee ("Luis Suarez", 7,"gmail.com"));
//Test Code with the new Hashmap.
/*Store.print();
Store.clear();
Store.print();
Store.add(new Employee ("James O' Carroll", 18,"hotmail.com"));
Store.add(new Employee ("Andy Carroll", 1171,"yahoo.com"));
Store.add(new Employee ("Luis Suarez", 7,"gmail.com"));
Store.print();
Store.remove("Andy Carroll");
Store.print();*/
//********************************************************************
//Switch Statement for use of a menu.
int choice;
do {
choice = getMenuChoice("1.\tLibrarian\n2.\tPublic User\n3.\tExit\n\n", 3, "Please enter choice:", "Error [1,3] only");
switch (choice) {
case 1:
System.out.println("Librarian Functionality...\n");
break;
case 2:
System.out.println("Public User functionality...\n");
break;
case 3:
System.out.println("Program Finished");
}
}
while (choice != 3);
}
//********************************************************************
public static int getMenuChoice(String menuString, int limit, String prompt, String errorMessage)
{
System.out.println(menuString);
int choice = inputAndValidateInt(1, limit, prompt, errorMessage);
return choice;
}
//********************************************************************
public static int inputAndValidateInt(int min, int max, String prompt, String errorMessage) {
int number;
boolean valid;
do {
System.out.print(prompt);
number = keyboard.nextInt();
valid = number <= max && number >= min;
if (!valid) {
System.out.println(errorMessage);
}
} while (!valid);
return number;
}
//********************************************************************
}
//Imports:
//********************************************************************
//Employee Class.
public class Employee
{
//Variables.
private String employeeName;
private int employeeId;
private String employeeEmail;
//********************************************************************
//Constructor.
public Employee(String employeeName, int employeeId, String employeeEmail)
{
this.employeeName = employeeName;
this.employeeId = employeeId;
this.employeeEmail = employeeEmail;
}
//********************************************************************
//Getters.
public String getEmployeeEmail() {
return employeeEmail;
}
public void setEmployeeEmail(String employeeEmail) {
this.employeeEmail = employeeEmail;
}
public String getEmployeeName() {
return employeeName;
}
public int getEmployeeId() {
return employeeId;
}
//********************************************************************
//toString method.
public String toString() {
return "Employee [employeeName=" + employeeName + ", employeeId="
+ employeeId + ", employeeEmail=" + employeeEmail + "]";
}
//********************************************************************
}
//Imports.
import java.util.HashMap;
//********************************************************************
import java.util.Map;
public class EmployeeStore
{
HashMap<String, Employee> map;
//Constructor.
public EmployeeStore()
{
map = new HashMap<String,Employee>();
}
//********************************************************************
//Hashmap Methods.
//Add to the Hashmap : Employee.
public void add(Employee obj)
{
map.put(obj.getEmployeeName(), obj);
}
//********************************************************************
//Remove from the Hashmap : Employee.
public void remove(String key)
{
//Remove the Employee by name.
map.remove(key);
}
//********************************************************************
//Clear the Hashmap : Employee.
public void clear()
{
map.clear();
}
//********************************************************************
//Print the Hashmap : Employee.
public void print()
{
System.out.println("\n********Employee's in the Company.********");
for (Employee employee : map.values())
{
System.out.println("Employee Name:\t" + employee.getEmployeeName());
System.out.println("Employee Id:\t" + employee.getEmployeeId());
System.out.println("E-mail:\t"+ employee.getEmployeeEmail());
}
}
//********************************************************************
//********************************************************************
}

You'll need to fetch the Employee object from the HashMap, then modify the object. For example, to change the email:
//in class EmployeeStore
String email = somehowGetNewEmail();
Employee toEdit = map.get(somehowGetName());
toEdit.setEmail(email)
Alternately:
//in EmployeeStore
public Employee get(String name){
return map.get(name);
}
//in any class with reference to an EmployeeStore "store"
store.get(name).editSomething(something);

A HashMap stores references to objects. That means when you read ("get") an object from a HashMap and make changes to its attributes, the changes will be carried over without you having to write it back to the HashMap.
So all your edit method has to do is call map.get(name) and make the changes to the returned Employee object. Note that you can not change the key of the HashMap that way. In order to "rename" an employee, you have to remove the value of the old key from the hash map and insert it under a new key.

Related

Using array to store and manipulate objects data with java

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];
}
}

How to create an arraylist using polymorphism?

I am trying to create an array list that contains all employees and is able to handle any type of employee. I also have to load the data onto to the list The class I'm using is called payroll. This is what I have so far:
The employee class looks like this:
import java.util.*;
public abstract class Employee
{
private String name, employeeNum, department;
private char type;
public Employee()
{
name ="";
employeeNum = "";
department = "";
}
public Employee(String Name, String EmpNum, String Depart)
{
name = Name;
employeeNum = EmpNum;
department = Depart;
}
//public EMpoy
public String getName()
{
return name;
}
public String getEmployeeNum()
{
return employeeNum;
}
public String getDepartment()
{
return department;
}
public char getType()
{
return type;
}
public void setName(String Name)
{
name = Name;
}
public void setEmployeeNum(String EmpNum)
{
employeeNum = EmpNum;
}
public void setDepartment(String Depart)
{
department = Depart;
}
public String toString()
{
String str;
str = "Employee Name: " + name + "\n"
+ "Employee Number: " + employeeNum + "\n"
+ "Employee Department: " + department + "\n";
return str;
}
}
The payroll class looks like this so far:
import java.util.*;
import java.io.*;
public class Payroll
{
private ArrayList<Employee> list = new ArrayList<Employee>();
private String fileName;
public Payroll()
{
}
public void fileName(String[] args)
{
Scanner kb = new Scanner(System.in);
System.out.println("InsertFileName");
String fileName1 = kb.next();
fileName = fileName1 + ".txt";
}
public void loadData() throws FileNotFoundException
{
Scanner s = new Scanner(new File(fileName));
while (s.hasNext())
{
String name = s.next();
String employeeNum = s.next();
String department = s.next();
//String typeString = s.next();
//char type = typeString.toUpperCase().charAt(0);
char type = s.next().toUpperCase().charAt(0);
if (type == 'S')
{
double yearlySalary = s.nextDouble();
list.add(new Salary (name, employeeNum, department, yearlySalary));
}
else if (type == 'H')
{
double hourlyPayRate = s.nextDouble();
String hours = s.next();
int hoursWorked = Integer.parseInt(hours);
list.add(new Hourly (name, employeeNum, department, hourlyPayRate, hoursWorked));
}
else if (type == 'C')
{
int numOfWeeks = s.nextInt();
double baseWeeklySalary = s.nextDouble();
int salesThisWeek = s.nextInt();
int salesThisYear = s.nextInt();
double commissionRate = s.nextDouble();
list.add(new Commission (name, employeeNum, department, numOfWeeks, baseWeeklySalary, salesThisWeek, salesThisYear, commissionRate));
}
}
s.close();
}
Now I know I'm supposed to make the arraylist in the constructor, that's what I'm having trouble with. How can I make the list using polymorphism to get every employee? Thanks.
Hi Srk93 You are getting error as your list contains the references of Employee class and Employee class does't have getCommissionRate method. You can call on Employee reference which are declared in Employee class. Create abstact method of calculateSalary() and implement in all your child classes.
Its duplicate of "cannot find symbol: method" but the method is declared

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);

Collection object can't show output showing some undefined value in java, Arraylist, Collection

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);
}
}

HashMapStore. Print Method not showing correct output

I have looked online and i havent been able to fix a problem that i am having. I am making an employee store using a hashMap but im not sure whether i am supposed to print the toString() or the theEntry.getKey() as i have in my current version. When using the getKey() method i am getting the wrong output which is:
*Employee's in the Company.***
Employee Name: James O' Carroll
Employee Id: James O' Carroll
E-mail: James O' Carroll
As you can see in the MainApp i want Store.add(new Employee ("James O' Carroll", 18,"hotmail.com")); to be the output.
I will paste my code:
//MainApp.
public class MainApp
{
public static void main(String[] args)
{
new MainApp().start();
}
public void start()
{
EmployeeStore Store = new EmployeeStore();
Store.add(new Employee ("James O' Carroll", 18,"hotmail.com"));
Store.print();
}
}
//Employee
//Imports:
//********************************************************************
//Employee Class.
public class Employee
{
//Variables.
private String employeeName;
private int employeeId;
private String employeeEmail;
//********************************************************************
//Constructor.
public Employee(String employeeName, int employeeId, String employeeEmail)
{
this.employeeName = employeeName;
this.employeeId = employeeId;
this.employeeEmail = employeeEmail;
}
//********************************************************************
//Getters.
public String getEmployeeEmail() {
return employeeEmail;
}
public void setEmployeeEmail(String employeeEmail) {
this.employeeEmail = employeeEmail;
}
public String getEmployeeName() {
return employeeName;
}
public int getEmployeeId() {
return employeeId;
}
//********************************************************************
//toString method.
public String toString() {
return "Employee [employeeName=" + employeeName + ", employeeId="
+ employeeId + ", employeeEmail=" + employeeEmail + "]";
}
//********************************************************************
}
//EmployeeStore.
//Imports.
import java.util.HashMap;
//********************************************************************
import java.util.Map;
public class EmployeeStore
{
HashMap<String, Employee> map;
//Constructor.
public EmployeeStore()
{
map = new HashMap<String,Employee>();
}
//********************************************************************
//Hashmap Methods.
//Add to the Hashmap : Employee.
public void add(Employee obj)
{
map.put(obj.getEmployeeName(), obj);
}
//********************************************************************
//Remove from the Hashmap : Employee.
public void remove(String key)
{
//Remove the Employee by name.
map.remove(key);
}
//********************************************************************
//Print the Hashmap : Employee.
public void print()
{
System.out.println("\n********Employee's in the Company.********");
for(Map.Entry<String, Employee> theEntry : map.entrySet())
{
System.out.println("Employee Name:\t" + theEntry.getKey());
System.out.println("Employee Id:\t" + theEntry.getKey());
System.out.println("E-mail:\t "+ theEntry.getKey());
}
}
//********************************************************************
//********************************************************************
}
This is clearly wrong:
for(Map.Entry<String, Employee> theEntry : map.entrySet())
{
System.out.println("Employee Name:\t" + theEntry.getKey());
System.out.println("Employee Id:\t" + theEntry.getKey());
System.out.println("E-mail:\t "+ theEntry.getKey());
}
You're printing the same value three times - how could it be the name, ID and email address? You're printing the key from the entry, which is always the name. You want the value of the entry.
You want this:
// This assumes you've renamed all the properties in Employee to be more
// sensible - there's no point in including the "employee" part - we already
// know we're calling a method on Employee
for (Employee employee : map.values())
{
System.out.println("Employee Name:\t" + employee.getName());
System.out.println("Employee Id:\t" + employee.getId());
System.out.println("E-mail:\t "+ employee.getEmail());
}
(Or just print employee of course. It depends on what you want the output to be.)
You'll want to iterate over the values of the map. By doing such, you'll get Employee instances in return and can simply define your print() method as follows,
public void print(){
for(Employee e : map.values()){
System.out.println(e);
}
}
Note that you do not need to explicitly invoke toString() because println will automatically do that for you.

Categories