HashMapStore. Print Method not showing correct output - java

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.

Related

Java Packages Concepts

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 .

"constructor Employee in class Employee cannot be applied to given types;"

I seem to be getting the constructor Employee in class Employee cannot be applied to given types; error and I'm not sure how to fix it. Im fairly new to coding so the simpler explanation the better.
method where the error occurs
specifically the "new Employee();" in the first line
Collections.sort(employees, new Employee());
System.out.println("\nFirst and Last Names of Employees sorted based on first Name\n");
for (Employee employee : employees) {
System.out.println("First Name: " + employee.getfirstName() + " Last Name: " + employee.getlastName()
+ " Salary: " + employee.getSalary());
}
List<Employee> newHirees = readFile(hirefile);
// Add new Hired employees
employees.addAll(newHirees);
Collections.sort(employees, new Employee());
System.out.println("\nFirst and Last Names of Employees sorted based on first Name after adding new hires\n");
for (Employee employee : employees) {
System.out.println("First Name: " + employee.getFirstName() + " Last Name: " + employee.getLastName()
+ " Salary: " + employee.getSalaryPaid());
}
List<Employee> firedEmployees = readFile(firefile);
System.out.println("\nFirst and Last Names of Employees After removing fired employees\n");
for (Employee fired : firedEmployees) {
String firstName=fired.getFirstName();
String lastname=fired.getLastName();
for (Employee employee : employees) {
if (employee.getFirstName().trim().equals(firstName)
&& employee.getLastName().equals(lastname)) {
employees.remove(employee);
}
}
}
for (Employee employee : employees) {
System.out.println("First Name: " + employee.getFirstName() + " Last Name: " + employee.getLastName());
}
}
//Employee class
public class Employee{
String firstName;
String lastName;
String gender;
int tenure;
String rate;
double salary;
public Employee( String firstName, String lastName,String gender,int tenure, String rate,double salary )
{
this.firstName=firstName;
this.lastName=lastName;
this.gender=gender;
this.tenure=tenure;
this.rate=rate;
this.salary=salary;
}
//get and set methods
public void setfirstName(String nm) {
this.firstName=nm;}
public void setlastName(String nm) {
this.lastName=nm;}
String getfirstName() {
return this.firstName;}
String getlastName() {
return this.lastName;}
public void setGender(String nm) {
this.gender=nm;}
public void setRate(String nm) {
this.rate=nm;}
String getGender(){
return this.gender;}
String getRate(){
return this.rate;}
void setSalary(double pr){
this.salary=pr;}
double getSalary(){
return this.salary;}
void setTenure(int q){
this.tenure=q;}
int getTenure(){
return this.tenure;}
public String toString(){
String s=this.firstName+" "+this.lastName+" "+this.gender+" "+this.tenure+" "+
this.rate+" "+this.salary;
return(s);
}
}
You don't have a parameterless constructor, so new Employee() won't work.
Why are you trying to pass that as a parameter there anyway?

Need various ways to come up with this output

I am supposed to come up with this output.
But I am getting this instead..
Here is my code:
import java.lang.*;
import java.util.*;
import java.io.*;
public class Sample{
private String name;
private Hashtable customers = new Hashtable();
private Hashtable movies = new Hashtable();
public Sample(String aName){
name = aName;
}
public String getName(){
return name;
}
public void setName(String aName){
name = aName;
}
public void addCustomer (Customer customer) {
customers.put(customer.getName(), customer);
}
public Customer getCustomer (String customerName) {
return (Customer)customers.get(customerName);
}
public void addMovie (Movie movie) {
movies.put(movie.getName(), movie);
}
public Movie getMovie (String movieName) {
return (Movie)movies.get(movieName);
}
public void error (String message) {
System.out.println ("ERROR: " + message);
}
public Enumeration getMovies() {
return movies.elements();
}
public Enumeration getCustomers() {
return customers.elements();
}
public void showAll() {
System.out.println ("name: "+ this.getName());
Enumeration kk = this.getCustomers();
while (kk.hasMoreElements()) {
Customer one = (Customer) kk.nextElement();
System.out.println (one.show());
}
Enumeration ff = this.getMovies();
while (ff.hasMoreElements()) {
Movie one = (Movie) ff.nextElement();
System.out.println (one.show());
}
}
public void test() {
Customer k1 = new Customer ("Jonah") ; this.addCustomer (k1);
Customer k2 = new Customer ("Hellen") ; this.addCustomer (k2);
Customer k3 = new Customer ("Agnes") ; this.addCustomer (k3) ;
Movie f1 = new Movie ("StarWars"); this.addMovie (f1) ;
Movie f2 = new Movie ("Shrek"); this.addMovie (f2) ;
System.out.println("-**-**- test part 1 -**-**-") ;
this.showAll();
System.out.println("-**-**- test part 2 -**-**-") ;
System.out.println("---" + k1.getName() + " rents " + f1.getName());
this.showAll();
k1.doRent(f1);
MY CUSTOMER CLASS:
package eric;
public class Customer {
String name;
public Customer(String nameCus){
name = nameCus;
}
public String getName(){
return name;
}
public String show(){
return name;
}
public void doRent(Movie f1) {
System.out.println(" -"+ " RentData" + "[" + getName() +"," + f1.getName() + "]" );
}
}
MY MOVIE CLASS:
public class Movie {
String name;
int x = 0;
public Movie(String nameMov){
name = nameMov;
}
public String getName(){
return name;
}
public String show(){
return name+"\n"+" - average: "+x +" days\n"+" - number of rentings: "+x ;
}
}
My problem is that i cannot find a way to fix -RentData [Jonah,StarWars] under the name Jonah... Instead it comes at the end of output.. I need some one to help me figure how am ganna do that.. thanks
You're calling k1.doRent(f1) before this.showAll() so naturally you will get the "RentData..." line printed before the names are printed. The way your code is now is not conducive to what you're trying to do at all. Your Customer class should have a member list called rentedMovies that is populated every time you call doRent(...) on a Customer object. Then, Customer.show() should print the name of the customer, followed by your "RentData..." stuff that comes from rentedMovies.

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

Edit Method for Hashmap EmployeeStore

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.

Categories