Last issue on Hashmap Ascending - java

Ok, I asked before my Employee hashmap. I believe I fixed both my Equals & CompareTo method, where now, the Strings uses "Equals" rather than "==", where my integer ID still uses "==". The compareTo now utilizes all my employee information to sort out. I think my problem lies with the main compiler. I'm trying to sort employees who have the same last name, and first name, by ID number. Here is both my files. I'll still play around with my main, but this is driving me bananass.
public class Employee implements Comparable {
private String firstName;
private String lastName;
private int id;
private int perfScale;
Employee() {
firstName = "";
lastName = "";
id = 0;
perfScale = 0;
}
Employee(String lastName, String firstName, int id, int perfScale){
this.firstName = firstName;
this.lastName = lastName;
this.id = id;
this.perfScale = perfScale;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public int getId() {
return id;
}
public void setId(int id){
this.id = id;
}
public int getPerfScale() {
return perfScale;
}
public void setPerfScale(int perfScale){
this.perfScale = perfScale;
}
public boolean equals(Object o) {
if(o instanceof Employee)
return(this.getLastName().equalsIgnoreCase(((Employee) o).getLastName()) &&
(this.getFirstName().equalsIgnoreCase(((Employee)o) .getFirstName()) &&
(this.getId() == ((Employee)o) .getId())));
else
return false;
}
public int compareTo(Object o) {
Employee e = (Employee) o;
if (this.lastName.equals(((Employee) o).lastName)){
if(this.firstName.equals(((Employee) o) .firstName)){
return (this.id - e.getId());}
else
return(this.firstName.compareTo(((Employee) o).firstName));
}
else
return(this.lastName.compareTo(((Employee) o).lastName));
}
public int hashCode(Object o){
return (int)this.id *
firstName.hashCode() *
lastName.hashCode();
}
public String toString()
{
return getLastName() + ", " + getFirstName() + " ID: " + getId() + " Rating: " + getPerfScale();
}
}
My 2nd main file that compiles. Every other case besides ascending function well. I'm playing around with treemaps with it. Before I was using getKey, then getValue(Where it gets my toString method in the other file). It used to omit the person with the same name that had the largest ID, now this omits the employee that has the smallest ID.
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
public class EmployeeTest {
public static void main(String[] args) {
TreeMap<String, Employee> firstAndLast = new TreeMap<String, Employee>();
TreeMap<Integer, Employee> idNumber = new TreeMap<Integer, Employee>();
TreeMap<Employee, Integer> performanceScale = new TreeMap<Employee, Integer>();
TreeSet<Integer> sort = new TreeSet<Integer>();
Scanner keyboardInput = new Scanner(System.in);
boolean exit = false;
int choice;
while (exit != true) {
System.out.println("//-----MENU-----//");
System.out.println("1. Add an Employee ");
System.out.println("2. Remove an Employee ");
System.out.println("3. Modify performance scale ");
System.out.println("4. Print all the performance scale ");
System.out.println("5. Sort first and last name based on ID ");
System.out.println("6. Exit the program.");
System.out.print("Enter choice: ");
choice = keyboardInput.nextInt();
switch (choice) {
case 1:
addEmployee(firstAndLast, idNumber, performanceScale);
break;
case 2:
removeEmployee(firstAndLast, idNumber, performanceScale);
break;
case 3:
modifyPerformanceScale(idNumber, performanceScale);
break;
case 4:
printAllperfScale(performanceScale);
break;
case 5:
printLastNameAscending(firstAndLast, idNumber);
break;
case 6:
exit = true;
System.out.println("Exiting program...");
break;
default:
System.out
.println("Please choose a number from 1 - 5 from the menu.");
}
}// end while
} // end main
public static void addEmployee(TreeMap<String, Employee> firstAndLastMap,
TreeMap<Integer, Employee> idNumberMap,
TreeMap<Employee, Integer> performanceScale) {
Scanner keyboardInput = new Scanner(System.in);
String firstName;
String lastName;
int id;
int perfScale;
System.out.print("Enter first name for the Employee: ");
firstName = keyboardInput.nextLine();
System.out.print("Enter last name for the Employeer: ");
lastName = keyboardInput.nextLine();
System.out.print("Enter ID number of the Employee: ");
id = keyboardInput.nextInt();
System.out.print("Enter Performance Scale rating between 1 to 5: ");
perfScale = keyboardInput.nextInt();
Employee addEmployee = new Employee(lastName, firstName, id, perfScale);
firstAndLastMap.put(lastName + ", " + firstName, addEmployee);
idNumberMap.put(id, addEmployee);
//changed - Added(addEmployee,perfScale) from put(perfScale)
performanceScale.put(addEmployee, perfScale);
}
public static void removeEmployee(TreeMap<String, Employee> firstAndLastMap,
TreeMap<Integer, Employee> idNumberMap,
TreeMap<Employee, Integer> performanceScale) {
Scanner keyboardInput = new Scanner(System.in);
String firstName;
String lastName;
int id;
System.out.print("Enter First name of Employee you want to remove: ");
firstName = keyboardInput.nextLine();
System.out.print("Enter last name of Employee you want to remove: ");
lastName = keyboardInput.nextLine();
System.out.print("Enter ID number of Employee you want to remove: ");
id = keyboardInput.nextInt();
//System.out.println();
firstAndLastMap.remove(lastName + ", " + firstName);
idNumberMap.remove(id);
//should be remove(perfScale)
}
public static void modifyPerformanceScale(TreeMap<Integer, Employee> idNumber, TreeMap<Employee, Integer> performanceScale) {
System.out.print("Enter ID: ");
Scanner keyboardInput = new Scanner(System.in);
int idNumber1;
int modScale;
idNumber1 = keyboardInput.nextInt();
System.out.print("Enter the number you want to change to: ");
modScale = keyboardInput.nextInt();
Employee employee = idNumber.get(idNumber1);
performanceScale.put(employee, modScale);
}
public static void printAllperfScale(TreeMap<Employee,Integer> performanceScale) {
Set Employee1 = performanceScale.entrySet();
Iterator itr1 = Employee1.iterator();
while (itr1.hasNext()) {
Map.Entry me = (Map.Entry) itr1.next();
System.out.println(me.getValue());
}
}
public static void printLastNameAscending(TreeMap<String, Employee> firstAndLast,
TreeMap<Integer, Employee>idNumber) {
Set Employee2 = firstAndLast.entrySet();
Iterator itr2 = Employee2.iterator();
while (itr2.hasNext()) {
Map.Entry fe = (Map.Entry) itr2.next();
System.out.println(fe.getValue());
}
}

Related

Not able to execute Login method. Feel something is wrong with the object creation for populating the array: Any help is very much appreciated [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
Trying to create a bank management app. Not able to execute Login method after creating a new user. Feel something is wrong with the object creation for populating the Perons and Account arrays. Please help.
/Account class to hold account details/
public class Account extends Persons {
int accountNum;
int pin;
float checkingBal;
float savingBal;
float withDrawAmount;
float depositAmmount;
float transferAmount;
public Account(){ }
public Account(int accountNum, float checkingBal, float savingBal, int pin ){
this.accountNum = accountNum;
this.checkingBal = checkingBal;
this.savingBal = savingBal;
this.pin = pin;
}
public void setAccountNum(int accountNum){
this.accountNum = accountNum;
}
public void setPin(int pin){
this.pin = pin;
}
public int getAccountNum(){
return accountNum;
}
public int getPin(){
return pin;
}
public void withDraw(float withDrawAmount){
this.savingBal = this.savingBal - withDrawAmount;
}
public void deposit(float depositAmmount){
this.checkingBal = this.checkingBal + depositAmmount;
}
public void transfer(float transferAmount, String fromAccount, String toAccount){
if(fromAccount == "Checking" && toAccount == "Savings"){
this.checkingBal = this.checkingBal - transferAmount;
this.savingBal = this.savingBal + transferAmount;
}else if(fromAccount == "Savings" && toAccount == "Checking"){
this.savingBal = this.savingBal - transferAmount;
this.checkingBal = this.checkingBal + transferAmount;
}
System.out.print("Your New Checking Balance Is: "+this.checkingBal);
System.out.print("Your New Savings Balance Is: "+this.savingBal);
}
public float checkBalance(int accountNum){
float totalBalance = 0;
if(this.accountNum == accountNum){
totalBalance = this.checkingBal + this.savingBal;
}
return totalBalance;
}
}
/*******************************************************************************************************/
/Persons class to hold all the people having account./
import java.util.Date;
public class Persons {
String fname;
String lname;
int age;
String dob;
String address;
float yearlyIncome;
int accountNum;
public Persons(){}
public Persons(String fname, String lname, int age, String dob, String address, float yearlyIncome, int accountNum){
this.fname = fname;
this.lname = lname;
this.age = age;
this.dob = dob;
this.address = address;
this.yearlyIncome = yearlyIncome;
this.accountNum = accountNum;
}
public void setFname(String fname) {
this.fname = fname;
}
public void setLname(String lname) {
this.lname = lname;
}
public void setAge(int age) {
this.age = age;
}
public void setDob(String dob) {
this.dob = dob;
}
public void setAddress(String address) {
this.address = address;
}
public void setYearlyIncome(float yearlyIncome) {
this.yearlyIncome = yearlyIncome;
}
public void setAccountNum(int accountNum){
this.accountNum = accountNum;
}
public String getFname() {
return fname;
}
public String getLname() {
return lname;
}
public int getAge() {
return age;
}
public String getDob() {
return dob;
}
public String getAddress() {
return address;
}
public float getYearlyIncome() {
return yearlyIncome;
}
public int getAccountNum(){
return accountNum;
}
}
/*****************************************************************************************************/
/Java Main Class/
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Random;
import java.util.Scanner;
import java.util.Date;
public class Main {
public static void main(String[] args) {
Scanner scanf = new Scanner(System.in);
Persons people[] = new Persons[3];
Account personAccount[] = new Account[3];
float withdrawAmount;
float depositAmount;
float transferAmount;
int mainChoice;
int choice;
int counter = 0;
int userId = 0;
int loopBreak = 0;
int loginSuccess = -1;
while(loopBreak != -1){
System.out.println("================================================================================================");
System.out.println("Welcome To The California Bank :)");
System.out.println("1. Login..");
System.out.println("2. Create A New Customer.");
System.out.println("3. Done With Transactions.");
mainChoice = scanf.nextInt();
switch (mainChoice) {
case 1:
System.out.println("Please Enter Your Account Number:");
int accountNum = scanf.nextInt();
System.out.println("Please Enter Your Pin:");
int pin = scanf.nextInt();
for (int i = 0; i <= counter; i++) {
if (personAccount[i].getAccountNum() == accountNum && personAccount[i].getPin() == pin) {
System.out.println(personAccount[i].getAccountNum());
System.out.println(personAccount[i].getPin());
System.out.println("Customer Logged In and Validated.");
userId = i;
loginSuccess = 0;
} else {
System.out.println("Sorry You Are Not A Current Customer!");
loginSuccess = -1;
}
}
if(loginSuccess == 0){
System.out.println("======================================================================================");
System.out.println("What Else Would You Like To Do Today?");
System.out.println("1. Deposit.");
System.out.println("2. Withdraw.");
System.out.println("3. Transfer Money.");
System.out.println("4. Check Balance.");
choice = scanf.nextInt();
switch (choice) {
case 1:
System.out.println("How Much Money Would You Like To Deposit?");
depositAmount = scanf.nextFloat();
personAccount[userId].deposit(depositAmount);
break;
case 2:
System.out.println("How Much Money Would You Like To Withdraw Today?");
withdrawAmount = scanf.nextFloat();
personAccount[userId].withDraw(withdrawAmount);
break;
case 3:
System.out.println("How Much Money Would You Like To Withdraw Today?");
transferAmount = scanf.nextFloat();
System.out.println("1. Press 1 To Transfer From Checking to Savings.");
System.out.println("2. Press 2 To Transfer From Savings To Checking.");
int transferChoice;
transferChoice = scanf.nextInt();
if (transferChoice == 1) {
personAccount[userId].transfer(transferAmount, "Checking", "Savings");
} else {
personAccount[userId].transfer(transferAmount, "Savings", "Checking");
}
case 4:
System.out.println("Here Is Your Total Account Balance");
personAccount[userId].checkBalance(people[counter].accountNum);
break;
}
}
break;
case 2:
people[counter] = new Persons();
personAccount[counter] = new Account();
System.out.println("Please Enter Your First Name For The Account Creation:");
scanf.next();
String fName = scanf.nextLine();
System.out.println("Please Enter Your Last Name For The Account Creation:");
scanf.next();
String lName = scanf.nextLine();
people[counter].setFname(fName);
people[counter].setLname(lName);
System.out.println("Please Enter Your Age:");
int age = scanf.nextInt();
people[counter].setAge(age);
System.out.println("Please Enter Your Date Of Birth:");
String dob = scanf.next();
people[counter].setDob(dob);
System.out.println("Please Enter Your Address:");
scanf.next();
String address = scanf.nextLine();
people[counter].setAddress(address);
System.out.println("Please Enter Your Yearly Income:");
float annualIncome = scanf.nextFloat();
people[counter].setYearlyIncome(annualIncome);
System.out.println("Generating Your Account Number.....");
Random rand = new Random();
accountNum = rand.nextInt(100000);
people[counter].setAccountNum(accountNum);
personAccount[counter].setAccountNum(accountNum);
System.out.println("Your New Account Number Is: "+accountNum);
System.out.println("Please Enter A 4 Digit Pin");
pin = scanf.nextInt();
personAccount[counter].setPin(pin);
System.out.println("New Customer Created:");
counter++;
break;
case 3:
System.out.println("Thanks For Using The California Banking System. Goodbye!");
loopBreak = -1;
break;
}
}
}
}
Below is the error I am Getting after creating a user:
Login..
Create A New Customer.
Done With Transactions.
1
Please Enter Your Account Number:
90806
Please Enter Your Pin:
3333
90806
3333
Customer Logged In and Validated.
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Account.getAccountNum()" because "personAccount[i]" is null
at Main.main(Main.java:48)
There are so many things about your code, but first its explanation about your bug which is NullPointerException.
This exception is thrown when you for example try to call some methods on null elements. In your case you declared array as 3 elements and add only one Account (newly created). Then you iterate on array which have null elements (2nd and 3rd are null). You should get rid of this for loop or initialize array as 1 element sized = new Account[1] and then each time copy your new accounts to new array with bigger size. But it would be terrible solution. Another way (much better
Arrays are not size dynamic so you should use one of Collections https://www.javatpoint.com/collections-in-java for example List (ArrayList would be enough). I will show you how to improve your code, hope you will learn something from it.
Ok so here is the code:
Person (not persons, shouldn't be), don't use float for money, use BigDecimal, mark your fields as private or protected (read about encapsulation), descript your fields better, not like dob - write dateOfBirth, I use LocalDate here, dont use old Time api, better look at new Java Time Api, also you can count age of user by: currentDate - dateOfBirth
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
public class Person {
private String firstName;
private String lastName;
private int age;
private LocalDate dateOfBirth;
private String address;
private BigDecimal yearlyIncome;
private int accountNumber;
public Person() { }
public Person(String firstName, String lastName, int age, LocalDate dateOfBirth, String address, BigDecimal yearlyIncome, int accountNumber) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.dateOfBirth = dateOfBirth;
this.address = address;
this.yearlyIncome = yearlyIncome;
this.accountNumber = accountNumber;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public LocalDate getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(LocalDate dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public BigDecimal getYearlyIncome() {
return yearlyIncome;
}
public void setYearlyIncome(BigDecimal yearlyIncome) {
this.yearlyIncome = yearlyIncome;
}
public int getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(int accountNumber) {
this.accountNumber = accountNumber;
}
}
Ok, next Account
You should read about super() keyword to call methods or constructors from parent class, I used it here just to show you how to do it, you give it to parent and set account class fields
import java.math.BigDecimal;
public class Account extends Person {
private int accountNumber;
private int pin;
private BigDecimal checkingBalance = BigDecimal.ZERO;
private BigDecimal savingBalance = BigDecimal.ZERO;
public Account() { }
public Account(int accountNumber, int pin, BigDecimal checkingBalance, BigDecimal savingBalance){
this.accountNumber = accountNumber;
this.checkingBalance = checkingBalance;
this.savingBalance = savingBalance;
this.pin = pin;
}
public int getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(int accountNumber) {
this.accountNumber = accountNumber;
}
public int getPin() {
return pin;
}
public void setPin(int pin) {
this.pin = pin;
}
public void withDraw(BigDecimal withDrawAmount){
this.savingBalance = this.savingBalance.subtract(withDrawAmount);
}
public void deposit(BigDecimal depositAmmount){
this.checkingBalance = this.checkingBalance.subtract(depositAmmount);
}
public void transfer(BigDecimal transferAmount, String fromAccount, String toAccount){
if(fromAccount.equals("Checking") && toAccount.equals("Savings")){
this.checkingBalance = this.checkingBalance.subtract(transferAmount);
this.savingBalance = this.savingBalance.add(transferAmount);
}else if(fromAccount.equals("Savings") && toAccount.equals("Checking")){
this.savingBalance = this.savingBalance.subtract(transferAmount);
this.checkingBalance = this.checkingBalance.add(transferAmount);
}
System.out.print("Your New Checking Balance Is: " + this.checkingBalance);
System.out.print("Your New Savings Balance Is: " + this.savingBalance);
}
public BigDecimal checkBalance(){
return this.checkingBalance.add(this.savingBalance);
}
}
Main
I improve a little Main class, you can see that I use List personsAccount, Collections are dynamic you can add as many elements as you want, means that you use collection of type account, you can do it like List too but read about inheritance and generics first. I add 5th option to back to main menu, also use do while option, 1 list is enough, you don't need persons and accounts arrays.
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class Main {
private static final Scanner scanner = new Scanner(System.in);
//if you use java 8 or above you can just do it like = new ArrayList<>();
//static is here just because of example, you should reconsider it
private static final List<Account> personsAccounts = new ArrayList<Account>();
public static void main(String[] args) {
BigDecimal withdrawAmount;
BigDecimal depositAmount;
BigDecimal transferAmount;
int mainChoice;
int choice;
boolean session = true;
Account currentLoggedAccount = new Account();
int loginSuccess = -1;
while (session) {
System.out.println("================================================================================================");
System.out.println("Welcome To The California Bank :)");
System.out.println("1. Login..");
System.out.println("2. Create A New Customer.");
System.out.println("3. Done With Transactions.");
mainChoice = scanner.nextInt();
switch (mainChoice) {
case 1:
System.out.println("Please Enter Your Account Number:");
int accountNumber = scanner.nextInt();
System.out.println("Please Enter Your Pin:");
int pin = scanner.nextInt();
for (int i = 0; i < personsAccounts.size(); i++) {
if (personsAccounts.get(i).getAccountNumber() == accountNumber && personsAccounts.get(i).getPin() == pin) {
System.out.println(personsAccounts.get(i).getAccountNumber());
System.out.println(personsAccounts.get(i).getPin());
System.out.println("Customer Logged In and Validated.");
currentLoggedAccount = personsAccounts.get(i);
loginSuccess = 0;
} else {
System.out.println("Sorry You Are Not A Current Customer!");
loginSuccess = -1;
}
}
if (loginSuccess == 0) {
do {
System.out.println("======================================================================================");
System.out.println("What Else Would You Like To Do Today?");
System.out.println("1. Deposit.");
System.out.println("2. Withdraw.");
System.out.println("3. Transfer Money.");
System.out.println("4. Check Balance.");
System.out.println("5. Back to main menu");
choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("How Much Money Would You Like To Deposit?");
depositAmount = scanner.nextBigDecimal();
currentLoggedAccount.deposit(depositAmount);
break;
// is case 2 and 3 is the same?
case 2:
System.out.println("How Much Money Would You Like To Withdraw Today?");
withdrawAmount = scanner.nextBigDecimal();
currentLoggedAccount.withDraw(withdrawAmount);
break;
case 3:
System.out.println("How Much Money Would You Like To Withdraw Today?");
transferAmount = scanner.nextBigDecimal();
System.out.println("1. Press 1 To Transfer From Checking to Savings.");
System.out.println("2. Press 2 To Transfer From Savings To Checking.");
int transferChoice;
transferChoice = scanner.nextInt();
if (transferChoice == 1) {
currentLoggedAccount.transfer(transferAmount, "Checking", "Savings");
} else {
currentLoggedAccount.transfer(transferAmount, "Savings", "Checking");
}
break;
case 4:
System.out.println("Here Is Your Total Account Balance");
currentLoggedAccount.checkBalance();
break;
default:
System.out.println("There is no option :(");
break;
}
}
while (choice != 5);
}
break;
case 2:
Account accountToAdd = new Account();
System.out.println("Please Enter Your First Name For The Account Creation:");
scanner.next();
String firstName = scanner.nextLine();
accountToAdd.setFirstName(firstName);
System.out.println("Please Enter Your Last Name For The Account Creation:");
scanner.next();
String lastName = scanner.nextLine();
accountToAdd.setLastName(lastName);
System.out.println("Please Enter Your Age:");
int age = scanner.nextInt();
accountToAdd.setAge(age);
System.out.println("Please Enter Your Date Of Birth:");
String date = scanner.next();
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd.MM.yyyy");
accountToAdd.setDateOfBirth(LocalDate.parse(date, dtf));
System.out.println("Please Enter Your Address:");
scanner.next();
String address = scanner.nextLine();
accountToAdd.setAddress(address);
System.out.println("Please Enter Your Yearly Income:");
BigDecimal annualIncome = scanner.nextBigDecimal();
accountToAdd.setYearlyIncome(annualIncome);
System.out.println("Generating Your Account Number.....");
Random rand = new Random();
//that is some kind of weir because what if somebody have this number yet? :D
int newAccountNumber = rand.nextInt(100000);
accountToAdd.setAccountNumber(newAccountNumber);
System.out.println("Your New Account Number Is: " + newAccountNumber);
System.out.println("Please Enter A 4 Digit Pin");
pin = scanner.nextInt();
accountToAdd.setPin(pin);
//adding new account to list
personsAccounts.add(accountToAdd);
System.out.println("New Customer Created:");
break;
case 3:
System.out.println("Thanks For Using The California Banking System. Goodbye!");
session = false;
break;
default:
System.out.println("There is no option :(");
break;
}
}
}
}
This code isn't perfect but it's working and its clearer, it can be improved by you as you wish. Hope you will learn something, read about java.Collections, java.Time, java Generics, you can also exchange normal for to for each loop like for(Account account : personsAccounts) {}. Cheers!

Unable to display all the elements of an arraylist

Menu driven program for adding and displaying employee details.
Taking input from the user for employee details.
Store it into array list and display it.
I have added the entries to a list but always the last entered data replaces all the elements in the list.
Taking input in switch case 1 and add it to an arraylist and displaying it in another case:
class Employee
{
Scanner sc = new Scanner(System.in);
int empid,n;
String empname, empdesignation, empdept, empproject;
public Employee() { }
public Employee(int id,String name,String desig,String dept,String proj)
{
this.empid=id;
this.empname=name;
this.empdesignation=desig;
this.empdept=dept;
this.empproject=proj;
}
public void setEmpNo() {
System.out.print("Enter the number of employees: ");
n = sc.nextInt();
}
public int getEmpNo() {
return n;
}
public int getID() {
return empid;
}
public void setID(int id) {
this.empid = id;
}
public String getName() {
return empname;
}
public void setName(String name) {
this.empname = name;
}
public String getDept() {
return empdept;
}
public void setDept(String dept) {
this.empdept = dept;
}
public String getDesig() {
return empdesignation;
}
public void setDesig(String desig) {
this.empdesignation = desig;
}
public String getProject() {
return empproject;
}
public void setProject(String proj) {
this.empproject = proj;
}
public void displayemp(int id, String name,
String dept, String designation, String project)
{
System.out.print("\n============================================================\n");
System.out.println("ID: " + id);
System.out.println("Name: " + name);
System.out.println("Department: " + dept);
System.out.println("Designation: " + designation);
System.out.println("Project: " + project);
System.out.print("\n============================================================\n");
}
}
public class trying
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int ch = 0, id, n, abc, count = 0, pcount = 0;
final int maxEmp=1000;
String name, designation, dept, pname, mgrname, project;
Employee emp5 = new Employee();
Project proj5 = new Project();
List<Employee> list = new ArrayList<Employee>();
List<Project> list1 = new ArrayList<Project>();
switch (ch) {
case 1:
emp5.setEmpNo();
int a = emp5.getEmpNo();
for (int i = 1; i < a+1; i++)
{
System.out.print("Enter ID: ");
id = sc.nextInt();
emp5.setID(id);
sc.nextLine();
System.out.print("Enter Name: ");
name = sc.nextLine();
emp5.setName(name);
System.out.print("Enter Department: ");
dept = sc.nextLine();
emp5.setDept(dept);
System.out.print("Enter Designation: ");
designation = sc.nextLine();
emp5.setDesig(designation);
System.out.print("Enter Project: ");
project = sc.nextLine();
emp5.setProject(project);
list.add(emp5);
}
break;
case 5:
System.out.println("Showing Employee Details:");
for(Employee e:list)
{
System.out.println(e.empid+" "+e.empname+" "+e.empdept+" "
+e.empdesignation+" "+e.empproject);
}
break;
}
} while (!(ch <= 0 || ch > 7));
}
I need to display all the entries of the array list, but the last entered data get repeatedly displayed.
Employee emp5 = new Employee();
This will fo inside the for loop after :
for (int i = 1; i < a+1; i++) {
Employee emp5 = new Employee();
....
}
You will have to create new employee obj. At this moment you are keep updating same obj.
Update
Try creating new obj after adding item in the list
list.add(emp5);
emp5 = new Employee();

Please find how to enter employee details,update,remove,displaying using hashmap

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
class Employee
{
private String Id;
private String Name;
private String Department;
private String Salary;
public Employee(String Id, String Name, String Department,
String Salary)
{
this.Id=Id;
this.Name=Name;
this.Department=Department;
this.Salary=Salary;
}
public String getId() {
return Id;
}
public void setId(String id) {
Id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getDepartment() {
return Department;
}
public void setDepartment(String department) {
Department = department;
}
public String getSalary() {
return Salary;
}
public void setSalary(String salary) {
Salary = salary;
}
public String toString()
{
return this.Id+"\t"+this.Name+"\t\t"+this.Department+"\t\t\t"+this.Salary;
}
}
public class Assignment4
{
public static void main(String[] args)
{
try {
Map< String, List<Employee> > m=new HashMap< String, List<Employee> >();
List<Employee> ListForFinance=new ArrayList<Employee>();
Scanner scn1=new Scanner(System.in);
String Id;
String Name;
String Department;
String Salary;
while(true)
{
System.out.print("\nThe Choices:\n1>add\n2>modification\n3>remove\n4>display\n\n");
System.out.println("Enter the choice: ");
System.out.println("To quit type -1");
int num=scn1.nextInt();
if(num == -1)
{
break;
}
switch(num)
{
case 1:
{
System.out.print("\nDepartment: ");
Department=scn1.next();
System.out.print("\nId: ";
Id=scn1.next();
System.out.print("\nName: ");
Name=scn1.next();
System.out.print("\nSalary: ");
Salary=scn1.next();
Employee employee1=new Employee(Id,Name,Department,Salary);
ListForFinance.add(employee1);
m.put(Department, ListForFinance);
break;
}
case 2:
{
System.out.println("Type Department to be modified");
Department=scn1.next();
System.out.println("Modification values");
System.out.print("\nId: ");
Id=scn1.next();
System.out.print("\nName: ");
Name=scn1.next();
System.out.print("\nSalary: ";
Salary=scn1.next();
Set<String> s=m.keySet();
Iterator<String> i=s.iterator();
Employee employee1=new Employee(Id,Name,Department,Salary);
m.get(Department.setId("Id");
ListForFinance.add(employee1);
m.put(Department, ListForFinance);
while(i.hasNext())
{
System.out.println(i.next());
}
break;
}
case 3:
{
System.out.println("=========================================================");
System.out.println("ID"+"\t"+"NAME"+"\t\t"+"DEPARTMENT"+"\t\t"+"SALARY");
System.out.println("=========================================================");
Set<String> s=m.keySet();
Iterator<String> i=s.iterator();
while(i.hasNext())
{
String dept=i.next();
List<Employee> employees=m.get(dept);
for(int j=0;j<employees.size();j++)
{
System.out.print("\n"+employees.get(j)+"\n\n");
}
}
break;
}
}
}
}
catch(Exception e)
{
System.out.println("NOTE: \n"+"Please enter specified key format..!!!");
System.out.println("======================================");
System.out.println("Now you are Signing out");
System.out.println("Thank You,Login Again");
System.out.println("======================================");
}
}
}
default:
System.out.println("=============================================================";
System.out.print("Wrong key Pressed,please enter the correct key\n";
System.out.println("Try again...!!!";
System.out.println("=============================================================";
}
}
}
Please find how to enter employee details,update,remove,displaying using hashmap wherin employee dept is taken as a key and id,name,salary is stored in the values using arraylist ......Currently Iam struck at CASE 2...PLease help me out
In CASE 1 i am trying to insert the employee details and in CASE 2 iam trying to modify the values .If i try to put any details with the same Dept it should create new entry...Even i should able to modify it,i am not getting how to do..PLease help me out
Your question is not clear,
For setting employee in list
Arraylist<Employee> list = new ArrayList<Employees>;
Employee emp = new Employee();
emp.setname("John");
emp.setEmpCode(1);
list.add(emp);
For getting employee from list just use this.
Employee emp = list.getItem(0);// change 0 to your position or make a loop to get all employees
import java.util.*; import java.util.concurrent.TimeUnit;
class Employee{
public String name; public String city; public String email; public String phone; public String age;`enter code here`
public Employee(String name,String city,String email,String age,String phone) { super(); this.name = name; this.city=city; this.email = email; this.age=age; this.phone = phone; }
public String getPhone() { return phone; }
public String getAge() { return age; }
public String getName() { return name; } public String getEmail() { return email; } public String getAddress() { return city; } public void setPhone(String phone) { this.phone = phone; } }
public class Display_Employee implements Comparator {
/* public int compare(Employee o1, Employee o2) { // in the case if when age is Integer return o1.getAge() - o2.getAge(); }*/ /public int compare(Employee o1, Employee o2) { //for short by Name return o1.getFirstName().compareTo(o2.getFirstName()); }/ public int compare(Employee o1, Employee o2) { //for short by Name return o1.getAge().compareTo(o2.getAge()); } public static void main(String[] args) throws Exception { int choice,i,size,mob_serch_result,email_serch_result; String name,city,email,phone,age,mob_serch,email_serch,update_search,choice_update,update_search_email; String name1,city1,email1,phone1,age1;
Scanner sc = new Scanner(System.in);
// Map< String, List > mapPhone=new HashMap< String, List >(); // Map< String, List > mapEmail=new HashMap< String, List >(); Map< String, Integer > mapEmail=new HashMap< String, Integer >(); Map< String, Integer > mapPhone=new HashMap< String, Integer >(); List list = new ArrayList(); //User Input /*System.out.println("How much details you want to Enter"); size=sc.nextInt() ; for(i=0;i<size;i++) {
System.out.println("\t\t\t\tEnter the "+(i+1)+" Employee Details \t\t\t\t\n"); System.out.println("Enter the name "); name=sc.next(); System.out.println("Enter the City "); city=sc.next(); System.out.println("Enter the email "); email=sc.next(); System.out.println("Enter the age "); age=sc.next(); System.out.println("Enter the MobNum "); phone=sc.next(); Employee employee=new Employee(name,city,email,age,phone); list.add(employee); mapPhone.put(phone,i); mapEmail.put(email,i); }*/
//Testing input Employee employee1=new Employee("Raj","Mumbai","raj#yahoo.com","27","7499031600"); list.add(employee1); phone="7499031600"; email="raj#yahoo.com"; mapPhone.put(phone,0); mapEmail.put(email,0); Employee employee2=new Employee("Rekha","Chennai","rekha#hotmail.com","24","9598551664"); list.add(employee2); phone1="9598551664"; email1="rekha#hotmail.com"; mapPhone.put(phone1,1); mapEmail.put(email1,1); Employee employee3=new Employee("Ram","Siliguri","ram#outlook.com","55","8563878480"); list.add(employee3); String phone2="8563878480"; String email2="ram#outlook.com"; mapPhone.put(phone2,2); mapEmail.put(email2,2); Employee employee4=new Employee("Lakhan","Bhopal","Lakhan#outlook.com","30","8563050698"); list.add(employee4); String phone3="8563050698"; String email3="Lakhan#outlook.com"; mapPhone.put(phone3,3); mapEmail.put(email3,3); Employee employee5=new Employee("Bharat","Ayodhya","Bharat#outlook.com","35","9044669201"); list.add(employee5); String phone4="9044669201"; String email4="Bharat#outlook.com"; mapPhone.put(phone4,4); mapEmail.put(email4,4 );
for (Employee s : list) { System.out.println("\n\n"+s.getName()+" " +s.getAddress()+" " +s.getAge()+" " +s.getEmail()+" " +s.getPhone()); } /Seaching part/ while(true) { System.out.println("==========================================================================================================="); System.out.println("Press 1 for Sort by age\nPress 2 for find the Person by mobile number\nPress 3 for find the Person by email\nPress 4 for update the mobiel number"); choice= sc.nextInt(); sc.nextLine(); switch(choice) { case 1: Collections.sort(list, new Display_Employee ()); for (Employee s : list) { System.out.println(" Name : "+s.getName()+" City : " +s.getAddress()+" Age : " +s.getAge()+" Email : " +s.getEmail()+" Phone : " +s.getPhone()); } System.out.println("===========================================================================================================");
break;
/*case 1 is Running perfectly*/
case 2:
System.out.println("Enter the mobiel number of Employee ");
mob_serch=sc.next();
mob_serch_result=mapPhone.get(mob_serch);
System.out.println("Mobile mob_serch_result is "+mob_serch_result);
Employee Emp_phone_obj=(Employee)list.get(mob_serch_result);
System.out.println("Employee Name: "+Emp_phone_obj.getName()+" Email : "+Emp_phone_obj.getEmail()+" Age : "+Emp_phone_obj.getAge()+" City : "+Emp_phone_obj.getAddress());
break; /*case 2 is Running perfectly*/
case 3:
System.out.println("Enter the emailId of Employee ");
email_serch=sc.nextLine();
email_serch_result=mapEmail.get(email_serch);
System.out.println("Email_serch_result is "+email_serch_result);
Employee Emp_email_obj=(Employee)list.get(email_serch_result);
System.out.println("Employee Name : "+Emp_email_obj.getName()+" Email : "+Emp_email_obj.getEmail()+" Age : "+Emp_email_obj.getAge()+" City : "+Emp_email_obj.getAddress());
break;
case 4:
System.out.println("Enter the mobile number ");
update_search= sc.next();
mob_serch_result=mapPhone.get(update_search);
Employee Emp_update_obj=(Employee)list.get(mob_serch_result);
update_search_email=Emp_update_obj.getEmail();
System.out.println("\t\t\t\t\t\t\tYour Search Result");
System.out.println(" Name: "+Emp_update_obj.getName()+" Email : "+Emp_update_obj.getEmail()+" Age : "+Emp_update_obj.getAge()+" City : "+Emp_update_obj.getAddress());
System.out.println("\t\t\t\t\t\t\tPress Y or y for Confirm and Update\tPress N or n for Cancle");
choice_update=sc.next();
if(choice_update.equalsIgnoreCase("Y")||choice_update.equalsIgnoreCase("y"))
{
mapPhone.remove(update_search);
mapEmail.remove(update_search_email);
list.remove(Emp_update_obj);
System.out.println("Enter the Firstname ");
name1=sc.next();
System.out.println("Enter the City ");
city1=sc.next();
System.out.println("Enter the email ");
email1=sc.next();
System.out.println("Enter the age ");
age1=sc.next();
System.out.println("Enter the MobNum ");
phone1=sc.next();
Employee employee=new Employee(name1,city1,email1,age1,phone1);
list.add(employee);
mapPhone.put(phone1, mob_serch_result);
mapEmail.put(email1, mob_serch_result);
}
break;
default:
System.out.println("\n\t****Please give a valid Input****\t\n");
break;
} }
}//End of main() method }//end of DisplayArrayList class
import java.util.*;
import java.util.concurrent.TimeUnit;
class Employee implements Comparator<Employee> {
private String name;
private String city;
private String email;
private String phone;
private int age;
public Employee(){}
public void setAge(Integer age) {
this.age = age;
}
public void setName(String Name) {
this.name = Name;
}
public void setEmail(String email) {
this.email = email;
}
public void setPhone(String phone) {
this.phone=null;
this.phone = phone;
}
public void setCity(String city) {
this.city = city;
}
public String getPhone() {
return phone;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public String getAddress() {
return city;
}
public int compare(Employee o1, Employee o2) { // in the case if when age is Integer
return o1.getAge() - o2.getAge();
}
}
public class Display_Employee {
public static void main(String[] args)
{
int choice,i,size,mob_serch_result,email_serch_result,age,age1;
String name,city,email,phone,mob_serch,email_serch,update_search,choice_update,update_search_email;
String name1,city1,email1,phone1,Update_choice,choice_update_for_phone,choice_update_for_email;
Scanner sc = new Scanner(System.in);
Map< String, Integer > mapEmail=new HashMap< String, Integer >();
Map< String, Integer > mapPhone=new HashMap< String, Integer >();
List<Employee> list = new ArrayList<Employee>();
/*
System.out.println("How much details you want to Enter");
size=sc.nextInt() ;
for(i=0;i<size;i++)
{
System.out.println("\t\t\t\tEnter the "+(i+1)+" Employee Details \t\t\t\t\n");
System.out.println("Enter the name ");
name=sc.next();
System.out.println("Enter the City ");
city=sc.next();
System.out.println("Enter the email ");
email=sc.next();
System.out.println("Enter the age ");
age=sc.nextInt();
System.out.println("Enter the MobNum ");
phone=sc.next();
Employee employee=new Employee();
employee.setAge(age);
employee.setName(name);
employee.setCity(city);
employee.setPhone(phone);
employee.setEmail(email);
list.add(employee);
mapPhone.put(phone,i);
mapEmail.put(email,i);
}*/
/*Test input Start*/
name="Anoop";
city="kanpur";
email="anoop#gmail.com";
age=23;
phone="9415418279";
Employee employee=new Employee();
employee.setAge(age);
employee.setName(name);
employee.setCity(city);
employee.setPhone(phone);
employee.setEmail(email);
list.add(employee);
mapPhone.put(phone,0);
mapEmail.put(email,0);
/*Test input end*/
for (Employee s : list)
{
System.out.println("\n\n"+s.getName()+" " +s.getAddress()+" " +s.getAge()+" " +s.getEmail()+" " +s.getPhone());
}
while(true)
{
System.out.println("===========================================================================================================");
System.out.println("Press 1 for Sort by age\nPress 2 for find the Person by mobile number\nPress 3 for find the Person by email\nPress 4 for update the mobiel number\nPress 5 for print list and free the varible ");
choice= sc.nextInt();
sc.nextLine();
switch(choice)
{
case 1:
Collections.sort(list,new Employee());
for (Employee s : list)
{
System.out.println(" Name : "+s.getName()+" City : " +s.getAddress()+" Age : " +s.getAge()+" Email : " +s.getEmail()+" Phone : " +s.getPhone());
}
System.out.println("===========================================================================================================");
break;
case 2:
System.out.println("Enter the mobile number of Employee ");
mob_serch=sc.next();
mob_serch_result=mapPhone.get(mob_serch);
System.out.println("Mobile mob_serch_result is "+mob_serch_result);
Employee Emp_phone_obj=(Employee)list.get(mob_serch_result);
System.out.println("Employee Name: "+Emp_phone_obj.getName()+" Email : "+Emp_phone_obj.getEmail()+" Age : "+Emp_phone_obj.getAge()+" City : "+Emp_phone_obj.getAddress());
break;
case 3:
System.out.println("Enter the emailId of Employee ");
email_serch=sc.nextLine();
email_serch_result=mapEmail.get(email_serch);
System.out.println("Email_serch_result is "+email_serch_result);
Employee Emp_email_obj=(Employee)list.get(email_serch_result);
System.out.println("Employee Name : "+Emp_email_obj.getName()+" Email : "+Emp_email_obj.getEmail()+" Age : "+Emp_email_obj.getAge()+" City : "+Emp_email_obj.getAddress());
break;
case 4:
System.out.println("\033[H\033[2J"+"\n\n\t\t\tPress P to Edit PhoneNumber & Press E for Edit Email ");
choice_update_for_phone=sc.next();
choice_update_for_email=choice_update_for_phone;
if(choice_update_for_phone.equalsIgnoreCase("P")||choice_update_for_phone.equalsIgnoreCase("p"))
{
System.out.println("Enter the Old Mobile number ");
update_search=sc.next();
mob_serch_result=mapPhone.get(update_search);
System.out.println(" mob_serch_result "+mob_serch_result);
Employee Emp_update_obj_phone=(Employee)list.get(mob_serch_result);
System.out.println("\t\t\t\t\t\t\tYour Search Result");
System.out.println(" Name: "+Emp_update_obj_phone.getName()+" Email : "+Emp_update_obj_phone.getEmail()+" Age : "+Emp_update_obj_phone.getAge()+" City : "+Emp_update_obj_phone.getAddress());
System.out.println("\t\t\t\tPress Y or y for Confirm and Update\tPress N or n for Cancle");
choice_update=sc.next();
if(choice_update.equalsIgnoreCase("Y")||choice_update.equalsIgnoreCase("y"))
{
System.out.println("Enter the New MobNum ");
phone1=sc.next();
Emp_update_obj_phone.setPhone(phone1);
System.out.println("\t\t\t\tupdated entry is :\n");
mapPhone.put(phone1,mob_serch_result); //Map update
System.out.println(" Name: "+Emp_update_obj_phone.getName()+" Email : "+Emp_update_obj_phone.getEmail()+" Age : "+Emp_update_obj_phone.getAge()+" City : "+Emp_update_obj_phone.getAddress()+" PhoneNumber : "+Emp_update_obj_phone.getPhone());
}
}
else if(choice_update_for_email.equalsIgnoreCase("e")||choice_update_for_email.equalsIgnoreCase("E"))
{
System.out.println("Enter the old email ");
update_search_email= sc.next();
email_serch_result=mapEmail.get(update_search_email);
System.out.println(" email_serch_result = "+ email_serch_result);
Employee Emp_update_obj_email=(Employee)list.get(email_serch_result);
System.out.println("\t\t\t\t\t\t\tYour Search Result");
System.out.println(" Name: "+Emp_update_obj_email.getName()+" Email : "+Emp_update_obj_email.getEmail()+" Age : "+Emp_update_obj_email.getAge()+" City : "+Emp_update_obj_email.getAddress());
System.out.println("\t\t\t\t\t\t\tPress Y or y for Confirm and Update\tPress N or n for Cancle");
choice_update=sc.next();
if(choice_update.equalsIgnoreCase("Y")||choice_update.equalsIgnoreCase("y"))
{
System.out.println("Enter the new email ");
email1=sc.next();
Emp_update_obj_email.setEmail(email1);
mapEmail.put(email1,email_serch_result);
}
}
break;
case 5:
Iterator<Employee> itr=list.iterator();
while(itr.hasNext())
{
Employee employe = itr.next();
System.out.print(" name: "+employe.getName());
System.out.print(" email: "+employe.getEmail());
System.out.print(" age: "+employe.getAge());
System.out.println(" phone: "+employe.getPhone());
}
System.gc();
break;
default:
System.out.println("\n\t****Please give a valid Input****\t\n");
break;
}
}
}//End of main() method
}//end of DisplayArrayList class

how to revoe and display objects fom Map

I'm trying to write a program using a Map to map the details of an employee with the hobbies of the employee. The program should take the details of the employee and his/her hobbies as input and then store them as key/value pair in the map. Once the addition of details is complete, then the user should be able to list down all the employees, along with their hobbies and also should be able to view a particular employee's (by giving employee id as input), details and his/her hobbies . Also the user should be able to delete an employee based on the id of the employee.
I have tried as follows. But the method 'deleteEmployee()', 'isEmployeePresent()' and 'displayEmployees()' are erroneous
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
class Employee {
String designation, name;
Date dob;
int employeeID;
float salary;
public Employee(String designation, Date dob, int employeeID, String name,
float salary) {
this.designation = designation;
this.dob = dob;
this.employeeID = employeeID;
this.name = name;
this.salary = salary;
}
public String getDesignation() {
return designation;
}
public Date getDob() {
return dob;
}
public int getEmployeeID() {
return employeeID;
}
public String getName() {
return name;
}
public float getSalary() {
return salary;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public void setDob(Date dob) {
this.dob = dob;
}
public void setEmployeeID(int employeeID) {
this.employeeID = employeeID;
}
public void setName(String name) {
this.name = name;
}
public void setSalary(float salary) {
this.salary = salary;
}
}
class Hobby {
String hobbyDescription, hobbyName;
public Hobby(String hobbyName, String hobbyDescription) {
this.hobbyName = hobbyName;
this.hobbyDescription = hobbyDescription;
}
public String getHobbyName() {
return hobbyName;
}
public String getHobbyDescription() {
return hobbyDescription;
}
public void setHobbyName() {
this.hobbyName = hobbyName;
}
public void setHobbyDescription() {
this.hobbyDescription = hobbyDescription;
}
}
public class EmployeeManagement {
public static void main(String args[]) {
HashMap<Employee, Hobby> hm1 = new HashMap<Employee, Hobby>();
Scanner sc1 = new Scanner(System.in);
System.out.println("How many names do you want to add to the system? ");
int w = sc1.nextInt();
EmployeeManagement ob = new EmployeeManagement();
ob.addEmployees(w, hm1);
ob.displayEmployees(hm1);
while (true) {
System.out.println("1. Delete an employee");
System.out
.println("2. Check whether an employee is present or not");
System.out.println("3. Break the loop and terminates the program");
int ch = sc1.nextInt();
switch (ch) {
case 1:
System.out.println("Enter Employee-I'd:");
int p = sc1.nextInt();
ob.deleteEmployee(p, hm1);
ob.displayEmployees(hm1);
break;
case 2:
System.out.println("Enter Employee-I'd:");
int q = sc1.nextInt();
boolean b = ob.isEmployeePresent(q, hm1);
if (b == true)
System.out.println("The employee is present");
else
System.out.println("The employee is not present");
break;
case 3:
return;
}
}
}
public void addEmployees(int n, Map<Employee, Hobby> abc) {
Scanner sc = new Scanner(System.in);
Employee[] obj1 = new Employee[n];
Hobby[] obj2 = new Hobby[n];
for (int i = 0; i < n; i++) {
System.out.println("Enter Employee name:");
String nm = sc.next();
System.out.println("Enter designation:");
String des = sc.next();
System.out.println("Enter employeeI-D:");
int eId = sc.nextInt();
System.out.println("Enter salary:");
double sl1 = sc.nextDouble();
float sl = (float) sl1;
System.out.println("Enter Hobby-name:");
String hnm = sc.next();
System.out.println("Enter Hobby-description");
String hdes = sc.next();
System.out.println("Enter date-of-birth:");
String dt1 = sc.next();
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
try {
Date dt = formatter.parse(dt1);
obj1[i] = new Employee(des, dt, eId, nm, sl);
obj2[i] = new Hobby(hnm, hdes);
} catch (ParseException e) {
e.printStackTrace();
}
abc.put(obj1[i], obj2[i]);
}
}
public void deleteEmployee(int id, Map<Employee, Hobby> m1) {
if (m1.containsKey((Employee.getEmployeeID()) == id))
m1.remove(Employee);
}
public boolean isEmployeePresent(int id, Map<Employee, Hobby> m2) {
if (m2.containsKey((Employee.getEmployeeID()) == id))
return true;
else
return false;
}
public void displayEmployees(Map<Employee, Hobby> hm) {
for (Map.Entry<Employee, Hobby> m : hm.entrySet()) {
System.out.println(m.getKey() + " " + m.getValue());
}
}
}
You're triying to access Employee methods in a static way:
if(m1.containsKey((Employee.getEmployeeID())==id))
// ↑ here
You must get the instances of Employee inside the map and then compare with the id given:
public void deleteEmployee(int id,Map<Employee,Hobby> m1) {
// iterate in the map searching for the id
for (Entry<Employee, Hobby> entry : map.entrySet()) {
Employee e = entry.getKey(); // here you have the employee
Hobby h = entry.getValue(); // here you have the hobby
// check if this employee have same id than given
if(e.getEmployeeID() == id) { // map contains the employee
m1.remove(e);
}
}
NOTES:
I would recommend to return a boolean to check if employee has been updated, deleted, etc... public boolean deleteEmployee(int id,Map<Employee,Hobby> m1)
I would keep the employees in another way, HashMap does not allow duplicates, so you cannot save more than one Hobby in each employee if you don't declare it like HashMap<Employee, List<Hobby>>.

How do you retrieve all of the records that a user inputs into an arraylist in java

I am trying to retrieve every record that an arraylist contains. I have a class called ContactList which is the super class of another class called BusinessContacts. My first task is to print only the first name and last name of a contact. The second task is to print details of a contact that's related to its id number. The ContactList class has all the instance variables and the set/get methods and the toString() method. The BusinessContact class consists of only two instance variables that need to be appended to the ContactList class. How is can this be worked out? The code is below:
The ContactList class:
package newcontactapp;
public abstract class ContactList {
private int iD;
private String firstName;
private String lastName;
private String adDress;
private String phoneNumber;
private String emailAddress;
// six-argument constructor
public ContactList(int id, String first, String last, String address, String phone, String email) {
iD = id;
firstName = first;
lastName = last;
adDress = address;
phoneNumber = phone;
emailAddress = email;
}
public ContactList(){
}
public void displayMessage()
{
System.out.println("Welcome to the Contact Application!");
System.out.println();
}
public void displayMessageType(String type)
{
System.out.println("This is a " + type);
System.out.println();
}
public int getiD() {
return iD;
}
public void setiD(int id) {
iD = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String first) {
firstName = first;
}
public String getLastName() {
return lastName;
}
public void setLastName(String last) {
lastName = last;
}
public String getAdDress() {
return adDress;
}
public void setAdDress(String address) {
adDress = address;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phone) {
phoneNumber = phone;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String email) {
emailAddress = email;
}
public String toString(){
return getiD() + " " + getFirstName() + " " + getLastName() + " " + getAdDress() + " " + getPhoneNumber() + " " + getEmailAddress() + "\n" ;
}
}
The BusinessContacts class:
package newcontactapp;
public class BusinessContacts extends ContactList {
private String jobTitle;
private String orGanization;
//
public BusinessContacts(int id, String first, String last, String address, String phone, String email, String job, String organization){
super();
jobTitle = job;
orGanization = organization;
}
public BusinessContacts(){
}
public String getJobTitle() {
return jobTitle;
}
public void setJobTitle(String job) {
jobTitle = job;
}
public String getOrGanization() {
return orGanization;
}
public void setOrGanization(String organization) {
orGanization = organization;
}
//#Override
public String toString(){
return super.toString()+ " " + getJobTitle()+ " " + getOrGanization() + "\n";
}
}
Here is my main method class:
package newcontactapp;
import java.util.ArrayList;
//import java.util.Iterator;
import java.util.Scanner;
public class NewContactAppTest {
//ArrayList<ContactList> fullList = new ArrayList<>();
ArrayList<ContactList> bContacts = new ArrayList<>();
ArrayList<ContactList> pContacts = new ArrayList<>();
public static void main(String [] args)
{
ContactList myContactList = new ContactList() {};
myContactList.displayMessage();
new NewContactAppTest().go();
}
public void go()
{
ContactList myContactList = new ContactList() {};
System.out.println("Menu for inputting a Business Contact or Personal Contact");
System.out.println();
Scanner input = new Scanner(System.in);
System.out.println("Please enter a numeric choice below: ");
System.out.println();
System.out.println("1. Add a Business Contact");
System.out.println("2. Add a Personal Contact");
System.out.println("3. Display Contacts");
System.out.println("4. Quit");
System.out.println();
String choice = input.nextLine();
if(choice.contains("1")){
String type1 = "Business Contact";
myContactList.displayMessageType(type1);
businessInputs();
}
else if(choice.contains("2")){
String type2 = "Personal Contact";
myContactList.displayMessageType(type2);
personalInputs();
}
else if(choice.contains("3")) {
displayContacts();
displayRecord();
}
else if(choice.contains("4")){
endOfProgram();
}
}
public void businessInputs()
{
BusinessContacts myBcontacts = new BusinessContacts();
//ContactList myContactList = new ContactList() {};
//ContactList nameContacts = new ContactList() {};
bContacts.clear();
int id = 0;
myBcontacts.setiD(id);
Scanner in = new Scanner(System.in);
while(true){
id = id + 1;
myBcontacts.setiD(id);
//myContactList.setiD(id);
System.out.println("Enter first name ");
String firstName = in.nextLine();
//nameContacts.setFirstName(firstName);
//myContactList.setFirstName(firstName);
myBcontacts.setFirstName(firstName);
System.out.println("Enter last name: ");
String lastName = in.nextLine();
//nameContacts.setLastName(lastName);
//myContactList.setLastName(lastName);
myBcontacts.setLastName(lastName);
System.out.println("Enter address: ");
String address = in.nextLine();
//myContactList.setAdDress(address);
myBcontacts.setAdDress(address);
System.out.println("Enter phone number: ");
String phoneNumber = in.nextLine();
//myContactList.setPhoneNumber(phoneNumber);
myBcontacts.setPhoneNumber(phoneNumber);
System.out.println("Enter email address: ");
String emailAddress = in.nextLine();
//myContactList.setEmailAddress(emailAddress);
myBcontacts.setEmailAddress(emailAddress);
System.out.println("Enter job title: ");
String jobTitle = in.nextLine();
myBcontacts.setJobTitle(jobTitle);
System.out.println("Enter organization: ");
String organization = in.nextLine();
myBcontacts.setOrGanization(organization);
//bContacts.add(myContactList);
bContacts.add(myBcontacts);
//names.add(nameContacts);
//System.out.println("as entered:\n" + bContacts);
System.out.println();
System.out.println("Enter another contact?");
Scanner input = new Scanner(System.in);
String choice = input.nextLine();
if(choice.equalsIgnoreCase("Y")) {
continue;
}
else{
break;
}
}
//bContacts.add(myBcontacts);
go();
}
public void personalInputs(){
ContactList myContactList = new ContactList() {};
PersonalContacts myPcontacts = new PersonalContacts();
Scanner in = new Scanner(System.in);
int id;
id = 1;
while(true){
System.out.println("Enter first name; ");
String firstName = in.nextLine();
myContactList.setFirstName(firstName);
myPcontacts.setFirstName(firstName);
System.out.println("Enter last name: ");
String lastName = in.nextLine();
myContactList.setLastName(lastName);
myPcontacts.setLastName(lastName);
System.out.println("Enter address: ");
String address = in.nextLine();
myContactList.setAdDress(address);
myPcontacts.setAdDress(address);
System.out.println("Enter phone number: ");
String phoneNumber = in.nextLine();
myContactList.setPhoneNumber(phoneNumber);
myPcontacts.setPhoneNumber(phoneNumber);
System.out.println("Enter email address: ");
String emailAddress = in.nextLine();
myContactList.setEmailAddress(emailAddress);
myPcontacts.setEmailAddress(emailAddress);
System.out.println("Enter birth date");
String dateOfBirth = in.nextLine();
myPcontacts.setDateOfBirth(dateOfBirth);
//pContacts.add(myContactList);
pContacts.add(myPcontacts);
id = id + 1;
myContactList.setiD(id);
System.out.println();
System.out.println("Enter another contact?");
Scanner input = new Scanner(System.in);
String choice = input.nextLine();
if (choice.equalsIgnoreCase("y")) {
continue;
}
else{
break;
}
}
go();
}
public void displayContacts(){
System.out.println();
for(ContactList name : bContacts){
System.out.println(name.getiD() + " " + name.getFirstName()+ " " + name.getLastName());
}
}
public void displayRecord(){
System.out.println();
System.out.println("Do you wish to see details of contact?");
Scanner input = new Scanner(System.in);
String choice = input.nextLine();
if(choice.equalsIgnoreCase("Y")) {
System.out.println();
System.out.println("Enter the numeric key from the list to see more specific details of that record");
System.out.println();
Scanner key = new Scanner(System.in);
System.out.println();
ContactList record = new ContactList() {};
for(int i = 0; i < bContacts.size(); i++){
record = bContacts.get(i);
System.out.println(record.toString());
}
}
else{
go();
}
/* else{
System.out.println();
System.out.println("This is a Personal Contact");
System.out.println();
for(int j = 0; j < pContacts.size(); j++){
ContactList pList = pContacts.get(j);
pList = pContacts.get(j);
System.out.println(pList.toString());
}
}*/
}
public void endOfProgram(){
System.out.println("Thank you! Have a great day!");
Runtime.getRuntime().exit(0);
}
}
If you're looking to get a value based on ID, try making a method that iterates over the contents of the ArrayList to find one that matches:
public ContactList getContactList(int id) {
for (ContactList list : /*your ContactList List object*/) {
if (list.getiD() == id) {
return list;
}
}
return null;
}
This will return null if none is found, or the first result in the list.

Categories

Resources