how to revoe and display objects fom Map - java

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>>.

Related

How do I assign object from one class to another class and how do I calculate double and int inside an ArrayList?

I have an assignment but i have problem trying to do some part of it. Appreciate if anyone can give me a hand.
Assignment brief: https://pastebin.com/3PiqvfTE
Main Method: https://pastebin.com/J2kFzB3B
import java.util.ArrayList;
import java.util.Scanner;
public class mainMethod {
public static void main(String[] args) {
//scanner
Scanner scanner = new Scanner (System.in);
//subject object
Subject subject = new Subject (0,null,0);
System.out.println("How many subject do you want to enter: ");
int subjectNumber = scanner.nextInt();
for (int j = 0; j < subjectNumber; j++) {
//subject ID
System.out.println("Please enter the subject ID: ");
int subID = scanner.nextInt();
//subject Name
System.out.println("Please enter subject name: ");
String subName = scanner.next();
//subject fee
System.out.println("Please enter subject fee: ");
double subFee = scanner.nextDouble();
//add subject
subject.addSubject(subID, subName, subFee);
}
//display subject
System.out.println(subject.getSubject());
/*
//loop for part time teacher
System.out.println("Please enter how many part time teacher do you have: ");
int PTcounter = scanner.nextInt();
for (int i = 0; i < PTcounter; i++) {
*/
Teacher teach = new Teacher (0,null,null);
//teacher employee ID
System.out.println ("Please enter the teacher employee ID: ");
int tid = scanner.nextInt();
//teacher name
System.out.println("Please enter the teacher name: ");
String tname = scanner.next();
//teacher gender
System.out.println("Please enter the teacher gender: ");
String tgender = scanner.next();
//add teacher details
teach.addTeacher(tid, tname, tgender);
//display teacher details
System.out.println(teach.getTeacher());
//call address class
Address address = new Address (0,null,null,0);
//address house number
System.out.println("Please enter house number: ");
int addyNum = scanner.nextInt();
//address street name
System.out.println("Please enter street name: ");
String StreetName = scanner.next();
//address city
System.out.println("Please enter city: ");
String City = scanner.next();
//address post code
System.out.println("Please enter postcode: ");
int Postcode = scanner.nextInt();
//add address
address.addAddress(addyNum, StreetName, City, Postcode);
//display address
System.out.println(address.getAddress());
//call Part Time Salary class
PartTimeSalary ptSalary = new PartTimeSalary(0,0);
//max hours
System.out.println("Please enter maximum work hours: ");
int maxHours = scanner.nextInt();
//hourly rate
System.out.println("Please enter hourly rate: ");
double hourlyRate = scanner.nextDouble();
ptSalary.addPTSalary(maxHours, hourlyRate);
System.out.println(ptSalary.getHourlyRate());
//System.out.printf("Teacher details is %s, Subject details is %s, Address is %s", teach.toString(),subject.toString(),address.toString());
}
}
1st problem. I have a subject class and a teacher class. Teacher will be able to teach maximum of 4 subject. I have prompt user to enter subject details before entering teacher details, so when user enter teacher details they will be able to assign subject to teacher just by using the subjectID. I have problem implementing this. My subject is already store in an ArrayList but how to I connect this with teacher. And in the end the program will display what subject each teacher teaches.
Subject Class: https://pastebin.com/iBYFqYDN
import java.util.ArrayList;
import java.util.Arrays;
public class Subject {
private int subjectID;
private String subjectName;
private double fee;
private ArrayList <Subject> subjectList = new ArrayList <Subject>();
public Subject(int subjectID, String subjectName, double fee) {
this.subjectID = subjectID;
this.subjectName = subjectName;
this.fee = fee;
}
public int getSubjectID () {
return subjectID;
}
public void setSubjectID (int subjectID) {
this.subjectID = subjectID;
}
public String getSubjectName () {
return subjectName;
}
public void setSubjectName (String subjectName) {
this.subjectName = subjectName;
}
public double getFee () {
return fee;
}
public void setFee (double fee) {
this.fee = fee;
}
#Override
public String toString() {
return "[subjectID=" + subjectID + ", subjectName=" + subjectName + ", fee=" + fee + "]";
}
public void addSubject (int subjectID, String subjectName, double fee) {
subjectList.add(new Subject(subjectID, subjectName, fee) );
}
public String getSubject () {
return Arrays.toString(subjectList.toArray());
}
}
Teacher class: https://pastebin.com/Np7xUry2
import java.util.ArrayList;
import java.util.Arrays;
public class Teacher {
private int employeeID;
private String name;
private String gender;
private ArrayList <Teacher> teacherDetailsList;
public Teacher (int employeeID, String name, String gender) {
this.employeeID = employeeID;
this.name = name;
this.gender = gender;
this.teacherDetailsList = new ArrayList <Teacher>();
}
public int getEmployeeID () {
return employeeID;
}
public void setEmployeeID (int employeeID) {
this.employeeID = employeeID;
}
public String getName () {
return name;
}
public void setName (String name) {
this.name = name;
}
public String getGender () {
return gender;
}
public void setGender (String gender) {
this.gender = gender;
}
#Override
public String toString() {
return "[employeeID=" + employeeID + ", name=" + name + ", gender=" + gender + "]";
}
public void addTeacher (int employeeID, String name, String gender) {
teacherDetailsList.add(new Teacher (employeeID,name,gender));
}
public String getTeacher () {
return Arrays.toString(teacherDetailsList.toArray());
}
}
2nd problem. Teacher will either be part time or full time teacher. Part time teacher will have a maximum work hour they can work and an hourly rate they will be paid for, so the final salary of part time teacher will be "maximum hours" multiply by "hourly rate". I have store "hourly rate" and "maximum work hours" in an ArrayList but how do I call them to make the multiplication then displaying at the end.
Part time salary class: https://pastebin.com/iGKpu87Y
import java.util.ArrayList;
public class PartTimeSalary {
private int maxHour;
private double hourlyRate;
private double hourlySalary;
private ArrayList <PartTimeSalary> PTSalary = new ArrayList <PartTimeSalary>();
private ArrayList <Double> finalHourlySalary = new ArrayList <Double>();
public PartTimeSalary (int maxHour, double hourlyRate) {
this.maxHour = maxHour;
this.hourlyRate = hourlyRate;
}
public int getMaxHours () {
return maxHour;
}
public void setMaxHour (int maxHour) {
this.maxHour = maxHour;
}
public double getHourlyRate () {
return hourlyRate;
}
public void setHourlyRate (double hourlyRate) {
this.hourlyRate = hourlyRate;
}
public double getHourlySalary() {
hourlySalary = hourlyRate*maxHour;
return hourlySalary;
}
public void addPTSalary (int maxHour, double hourlyRate) {
PTSalary.add(new PartTimeSalary(maxHour,hourlyRate));
}
public void FinalHourlySalary (double hourlySalary) {
hourlySalary = hourlyRate * maxHour;
finalHourlySalary.add(hourlySalary);
}
public ArrayList<Double> getFinalSalary () {
return (new ArrayList <Double>());
}
}
3rd question. I have an address class which is suppose to be part of the Teacher class. I can't seem to connect the address class with teacher class.
Address class: https://pastebin.com/s2HN5p80
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Address {
private int houseNum;
private String streetName;
private String city;
private int postcode;
private List <Address> address = new ArrayList <Address>();
public Address (int houseNum, String streetName, String city, int postcode) {
this.houseNum = houseNum;
this.streetName = streetName;
this.city = city;
this.postcode = postcode;
}
public int getHouseNum() {
return houseNum;
}
public void setHouseNum (int houseNum) {
this.houseNum = houseNum;
}
public String getStreetName() {
return streetName;
}
public void setStreetName (String streetName) {
this.streetName = streetName;
}
public String getCity() {
return city;
}
public void setCity (String city) {
this.city = city;
}
public int getPostcode() {
return postcode;
}
public void setPostcode (int postcode) {
this.postcode = postcode;
}
public void addAddress (int houseNum, String streetName, String city, int postcode) {
address.add(new Address (houseNum,streetName,city,postcode));
}
#Override
public String toString() {
return "[houseNum=" + houseNum + ", streetName=" + streetName + ", city=" + city + ", postcode="
+ postcode + "]";
}
public String getAddress () {
return Arrays.toString(address.toArray());
}
}
Thank you 😃😊
Question 1)
Put the "teacherDetailsList" and "subjectList" ArrayLists in the main method, not the consructors. Add the teachers and subjects in main methods, not constructors.
Add a new ArrayList called "mySubjects" as a field for the Teacher Class
Add the following 2 method to the Teacher class:
public Teacher (int employeeID, String name, String gender, ArrayList<Subject> s) {
this.employeeID = employeeID;
this.name = name;
this.gender = gender;
this.mySubjects=s;
}
public Teacher (int employeeID, String name, String gender, Subject s) {
this.employeeID = employeeID;
this.name = name;
this.gender = gender;
this.mySubjects.add(s);
}
public void addSubject(Subject s, boolean b){
if(mySubjects.size()<4)mySubjects.add(s);
else throw OutOfBoundsError;
}
public void removeSubject(Subject s, boolean b){
mySubject.remove(s);
}
public void addSubject(Subject s){
s.changeTeacher(s);
}
public void removeSubject(Subject s){
mySubject.remove(s);
}
Add the following methods & fields to Student class
private Teacher teacher;
public Subject(int subjectID, String subjectName, double fee, Teacher t) {
this.subjectID = subjectID;
this.subjectName = subjectName;
this.fee = fee;
this.setTeacher(t);
}
public void setTeacher(Teacher t){
try{
t.addSubject(this);
teacher=t;
}
catch(OutOfBoundsError e){
System.out.println(t.getName()+" already has a full schedule.");
}
}
public void changeTeacher(Teacher t){
teacher.removeSubject(this);
teacher = t;
t.addSubject(this);
}
Question 2)
make a new double field, constructor parameter (for every constructor in the class), mutator method and accessor mutator called maxHour in the class Subject
add a double field to the teacher class called salary. If the teacher is part-time, set this to 0 in the constructor.
add this method to Teacher class:
public double getSalary(){
if(salary!=0) return salary;
double s=0;
for(Subject i: mySubjects) s+=i.getFee()*i.getMaxHours();
return s;
}
You honestly no longer need the PartTimeSalary class now.
Question 3
make a new Address field, constructor parameter (for every constructor in the class), mutator method and accessor mutator called myAddress in the class Teacher
Don't bother with the ArrayList stuff in your Address Class

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

3 separate ArrayList

ACME wants to layoff some employees. Using three ArrayLists, form three lists of employees. The first list will contain all the programmers, the second all the non-programming people making over one hundred thousand dollars, and the last all other people. Using separate loops print out the contents of each ArrayList. (The following are what I did, but not work... looking for help)
import java.util*;
class Employee
{
private String name;
private String address;
private String position;
private double salary;
private String getName()
{return name;}
public String getAddress()
{return address;}
public double getPosition()
{return position;}
public double getSalary()
{return salary;}
public void setName(String aName)
{name=aName;}
public void setAddress(String aAddress)
{address=aAddress;}
public void set(double aPosition)
{postion=aPosition;}
public void setSalary(double aSalary)
{salary=aSalary;}
public employee(String aName, String aAddress, double aPosition; double aSalary)
{
name=aName;
address=aAddress;
position=aPosition;
Salary=aSalary; }
public String toString()
{return name+address+position+salary;}
}
class employee
{public static void main(String[] args)
{Scanner in = new Scanner(System.in);
Employee[] Newemp=new Car[500];
for(int i=0, i<Newemp.length;i++)
{System.out.print(“Enter the name”);
String name=in.nextLine();
System.out.print(“Enter the address”);
String address=in.nextLine();
System.out.print(“Enter the position”);
double position=in.nextDouble();
System.out.print(“Enter the salary”);
double salary=in.nextInt() ;
in.nextLine();
Newemp[i]=new Employee(name, address, position, salary);
}
ArrayList<Employee>programmers=new ArrayList<Employee>();
ArrayList<Employee>nonprogrammers=new ArrayList<Employee>();
ArrayList<Employee>others=new ArrayList<Employee>();
for(int i=0; i<Newemp.salary; i++)
{if(Newemp[i]. getposition().equals(“programmer”))
programmers.add(Newemp[i]);
else if(Employee[i].getsalary()>100000
nonprogrammers.add(Newemp[i]);
else
others.add(Newemp[i]);
}
for(int i=0; i<programmer.();i++)
{
Employee<=programmer.get(i);
System.out.println(i);
}}}
i think this will help
for (int i = 0; i < Newemp.length; i++) {
if (Newemp[i].getPosition().equals("programmer")){
programmers.add(Newemp[i]);
System.out.println("programmers"+programmers);
}
else if (Newemp[i].getSalary()> 100000)
{
nonprogrammers.add(Newemp[i]);
System.out.println("salary 100000 thousand"+nonprogrammers);
} else{
others.add(Newemp[i]);
System.out.println("others"+others);
}
}
for (int i = 0; i < programmers.size(); i++) {
EmployeeData aa= programmers.get(i);
System.out.println("All aaray"+aa);
}
in your main()
for(int i=0; i < Newemp.salary; i++)
...
else if(Employee[i].getsalary()>100000
should be:
for(int i=0; Newemp[i] != null; i++)
...
else if([i].getsalary()>100000)
I hope you understand the concept of object, the methods & variables available with the array can not be mixed with others and vice-versa. length is a variable inside the array object which returns you the size. I would suggest instead of declaring a huge array and then iterating through it. Directly add your objects into an ArrayList as given below. I hope it helps.
import java.util.ArrayList;
import java.util.Scanner;
public class Employee {
private String name;
private String address;
private String position;
private double salary;`
public Employee(String aName, String aAddress, String aPosition,
double aSalary) {
name = aName;
address = aAddress;
position = aPosition;
salary = aSalary;
}
private String getName() {
return name;
}
public String getAddress() {
return address;
}
public String getPosition() {
return position;
}
public double getSalary() {
return salary;
}
public void setName(String aName) {
name = aName;
}
public void setAddress(String aAddress) {
address = aAddress;
}
public void set(String aPosition) {
position = aPosition;
}
public void setSalary(double aSalary) {
salary = aSalary;
}
public String toString() {
return name + address + position + salary;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int maxSize = 500;
ArrayList<Employee> programmers = new ArrayList<Employee>();
ArrayList<Employee> nonprogrammers = new ArrayList<Employee>();
ArrayList<Employee> others = new ArrayList<Employee>();
for (int i = 0; i < maxSize; i++) {
System.out.println("Enter the name");
String name = in.nextLine();
System.out.print("Enter the address");
String address = in.nextLine();
System.out.print("Enter the position");
String position = in.nextLine();
System.out.print("Enter the salary");
double salary = in.nextInt();
in.nextLine();
Employee newEmployee = new Employee(name, address, position, salary);
if (position.equals("programmer"))
programmers.add(newEmployee);
else if (salary > 100000)
nonprogrammers.add(newEmployee);
else
others.add(newEmployee);
}
}
}

Java - Adding 2 objects in an ArrayList

I'm pretty new to programming so I need help. I wanna add the SubjectGrades to the studentList ArrayList. But I think I'm doing the wrong way. What should I do for me to add the SubjectGrades to the ArrayList? Thanks
Here's my partial Main class.
import java.util.Scanner;
import java.util.ArrayList;
public class Main {
private static Scanner in;
public static void main(String[] args) {
ArrayList<Student> studentList = new ArrayList<Student>();
//ArrayList<SubjectGrades> Grades = new ArrayList<SubjectGrades>();
in = new Scanner(System.in);
String search, inSwitch1, inSwitch2;
int inp;
do {
SubjectGrades sGrade = new SubjectGrades();
Student student = new Student();
System.out.println("--------------------------------------");
System.out.println("What do you want to do?");
System.out.println("[1]Add Student");
System.out.println("[2]Find Student");
System.out.println("[3]Exit Program");
System.out.println("--------------------------------------");
inSwitch1 = in.next();
switch (inSwitch1) {
case "1":
System.out.println("Input student's Last Name:");
student.setLastName(in.next());
System.out.println("Input student's First Name:");
student.setFirstName(in.next());
System.out.println("Input student's course:");
student.setCourse(in.next());
System.out.println("Input student's birthday(mm/dd/yyyy)");
student.setBirthday(in.next());
System.out.println("Input Math grade:");
student.subjectGrade.setMathGrade(in.nextDouble());
System.out.println("Input English grade:");
student.subjectGrade.setEnglishGrade(in.nextDouble());
System.out.println("Input Filipino grade:");
student.subjectGrade.setFilipinoGrade(in.nextDouble());
System.out.println("Input Java grade:");
student.subjectGrade.setJavaGrade(in.nextDouble());
System.out.println("Input SoftEng grade:");
student.subjectGrade.setSoftEngGrade(in.nextDouble());
studentList.add(student);
studentList.add(student.setSubjectGrade(sGrade)); //Here it is that I want to add
break;
//end case 1
Here is my Student Class.
package santiago;
public class Student {
private String lastName;
private String firstName;
private String course;
private String birthday;
SubjectGrades subjectGrade = new SubjectGrades();
public SubjectGrades getSubjectGrade() {
return subjectGrade;
}
public void setSubjectGrade(SubjectGrades subjectGrade) {
this.subjectGrade = subjectGrade;
}
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 String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
}
And my SubjectGrades class
package santiago;
public class SubjectGrades{
Double mathGrade, englishGrade, filipinoGrade, javaGrade, softEngGrade, weightedAverage;
public Double getMathGrade() {
return mathGrade;
}
public void setMathGrade(Double mathGrade) {
this.mathGrade = mathGrade;
}
public Double getEnglishGrade() {
return englishGrade;
}
public void setEnglishGrade(Double englishGrade) {
this.englishGrade = englishGrade;
}
public Double getFilipinoGrade() {
return filipinoGrade;
}
public void setFilipinoGrade(Double filipinoGrade) {
this.filipinoGrade = filipinoGrade;
}
public Double getJavaGrade() {
return javaGrade;
}
public void setJavaGrade(Double javaGrade) {
this.javaGrade = javaGrade;
}
public Double getSoftEngGrade() {
return softEngGrade;
}
public void setSoftEngGrade(Double softEngGrade) {
this.softEngGrade = softEngGrade;
}
public Double getWeightedAverage(){
weightedAverage = ((mathGrade + englishGrade + filipinoGrade + javaGrade + softEngGrade)*3) / 15;
return weightedAverage;
}
public String getScholarStatus(){
String status = "";
if(weightedAverage <= 1.5) {
status = "full-scholar";
} else if (weightedAverage <= 1.75){
status = "half-scholar" ;
} else {
status = "not a scholar";
}
return status;
}
}
Your mistake:
studentList.add(student);
studentList.add(student.setSubjectGrade(sGrade));
You are adding the student, then trying to add a void. The return value of setSubjectGrade is void, so nothing will be added:
Just do:
student.setSubjectGrade(sGrade);
studentList.add(student);
Where sGrade is an Object of type SubjectGrades, which was populated in the same way
student.subjectGrade.setSoftEngGrade(in.nextDouble()); was populated.
Use
ArrayList <SubjectGrades> list;
in student class instead SubjectGrades subjectGrade = new SubjectGrades();.
and generate getters and setters
Just remove this line:
studentList.add(student.setSubjectGrade(sGrade)); //Here it is that I want to add
The way you have done it, the student object already has the subjectGrade attribute with its values set.
You can access it with studentList.get(0).getSubjectGrade()

Categories

Resources