How to create an arraylist using polymorphism? - java

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

Hi Srk93 You are getting error as your list contains the references of Employee class and Employee class does't have getCommissionRate method. You can call on Employee reference which are declared in Employee class. Create abstact method of calculateSalary() and implement in all your child classes.
Its duplicate of "cannot find symbol: method" but the method is declared

Related

How can I solve with Java's map containsKey() method?

I checked the code and saving data to the HashMap is correct, when typing ADD. Then after choosing option FIND I can get to the dedicated function but the method is unable to show me found object even if it is correct 100%.
Please check this code out and tell me why it does not find right objects in "public void showInfo(String name, String secondName)" for class Company that is sparked by TYPING "FIND" in class CompanyApp
import java.util.InputMismatchException;
import java.util.Objects;
import java.util.Scanner;
public class CompanyApp {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
options[] values = options.values();
int choose;
int EXIT_NR = 2;
Company ref = new Company();
do {
System.out.println("Available options: ");
for (options one : values) {
System.out.println(one.getDescription() + " - " + one.name());
}
System.out.println("Choose one: ");
try {
choose = options.valueOf(in.nextLine()).ordinal();
if (Objects.equals(EXIT_NR, choose)) break;
if (choose < 0 || choose >= options.values().length) {
throw new IllegalArgumentException("Choose 0, 1 or 2!");
}
options(choose);
} catch (InputMismatchException e) {
System.out.println("Choose a number ");
}
} while (1 == 1);
}
static void options(int choose){
Company ref = new Company();
Scanner info = new Scanner(System.in);
switch (choose){
case 0:
System.out.println("Type in the name of the worker: ");
String name = info.nextLine();
System.out.println("Type in the second name of the worker: ");
String secondName = info.nextLine();
System.out.println("Type in the salary: ");
double salary = info.nextDouble();
info.nextLine();
ref.add(new Employee(name, secondName, salary));
break;
case 1:
System.out.println("Type in the name of the worker you want to find: ");
String name2 = info.nextLine();
System.out.println("Type in the second name of the worker you want to
find: ");
String secondName2 = info.nextLine();
ref.showInfo(name2, secondName2);
break;
}
}
}
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class Company {
private Map<String, Employee> map = new HashMap<>();
public void add(Employee employee){
String key = employee.getName() + " " + employee.getSecondName();
if(!map.containsKey(key)){
map.put(key, employee);
System.out.println("Added object to map");}
}
public void showInfo(String name, String secondName){
String key = name + " " + secondName;
System.out.println("in showinfo method");
if(map.containsKey(key)){
System.out.println("found an object");
Employee employee = map.get(key);
System.out.println(employee.getName());
}}}
enum options {
ADD("Add employee "), FIND("Find employee"), EXIT("Exit program");
private String description;
options(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return "options{" +
"description='" + description + '\'' +
'}';
}
}
String name;
String secondName;
double salary;
public Employee(String name, String secondName, double salary) {
this.name = name;
this.secondName = secondName;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSecondName() {
return secondName;
}
public void setSecondName(String secondName) {
this.secondName = secondName;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
#Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", secondName='" + secondName + '\'' +
", salary=" + salary +
'}';
}
}
The problem is in the method static void options(int choose). You need to pass the Company-Object and use it there like this:
Call from main method (ref is the Company-Object you create in the main method)
options(choose, ref);
The options-method with the Company as second parameter:
static void options(int choose, Company ref){
Scanner info = new Scanner(System.in);
switch (choose){
case 0:
System.out.println("Type in the name of the worker: ");
String name = info.nextLine();
System.out.println("Type in the second name of the worker: ");
String secondName = info.nextLine();
System.out.println("Type in the salary: ");
double salary = info.nextDouble();
info.nextLine();
//use the passed Company here
ref.add(new Employee(name, secondName, salary));
break;
case 1:
System.out.println("Type in the name of the worker you want to find: ");
String name2 = info.nextLine();
System.out.println("Type in the second name of the worker you want to find: ");
String secondName2 = info.nextLine();
//and here
ref.showInfo(name2, secondName2);
break;
}
}
Explanation what is happening in your code
As mentioned, the problem is in the method static void options(int choose).
Here you create a new Company-Object which is not passed in any way to the main method.
This is what happens, when you use ADD and a FIND afterwards:
Call options from main method with ADD
new Company-Object is created in options
new Employee-Object is added to the Company from the previous point
the method ends -> the created Company-Object is "thrown away" (eligible for Garbage Collection)
Call options from main method with FIND
new Company-Object is created in options(therefore no Employees in it)
no Employee can be found, because there is no entry in the map of the newly created Company
The map is empty at the time when you're trying to get the data from it using FIND option. The reason for that is you recreate the Company object in the options method:
Company ref = new Company();
At the same time also the map is recreated so there are no records inside.
Also, the Company object in the main method is not used.

how to get input for an array of class in java?

I am new in java and I trying to get information
for five students and save them into an array of classes. how can I do this?
I want to use class person for five students whit different informations
import java.io.IOException;
import java.util.*;
public class exam
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
// I want to get and save information in this array
person[] f = new student[5];
}
}
class person defined for get name and family name.
import java.util.*;
public abstract class person {
Scanner scr = new Scanner(System.in);
private String name , fname;
public void SetName() {
System.out.println("enter name and familyNAme :");
name = scr.next();
}
public String getname() {
return name;
}
public void setfname () {
System.out.println("enter familyname:");
fname = scr.next();
}
public String getfname() {
return fname;
}
}
class student that inherits from the class person for get studentID and student Scores .
import java.util.*;
class student extends person {
float[] p = new float[5];
int id , sum ;
float min;
public void inputs() {
System.out.println("enter the id :");
id = scr.nextInt();
}
public void sumation() {
System.out.println("enter points of student:");
sum= 0;
for(int i = 0 ; i<5 ; i++){
p[i]=scr.nextFloat();
sum+=p[i];
}
}
public void miangin() {
min = (float)sum/4;
}
}
So first things first, when creating Java objects, refrain from getting input inside the object so that if you decide to change the way you get input (e.g. transition from command line to GUI) you don't need to modify the Java object.
Second, getters and setters should only get or set. This would save some confusion when debugging since we don't have to check these methods/functions.
So here's the person object:
public abstract class Person {
protected String name, fname;
public Person (String name, String fname) {
this.name = name;
this.fname = fname;
}
public void setName (String name) {
this.name = name;
}
public String getName () {
return name;
}
public void setFname (String fname) {
this.fname = fname;
}
public String getFname () {
return fname;
}
}
And here's the student object (tip: you can make as much constructors as you want to make object creation easier for you):
public class Student extends Person {
private float[] p;
private int id;
public Student (String name, String fname) {
this (name, fname, -1, null);
}
public Student (String name, String fname, int id, float[] p) {
super (name, fname);
this.id = id;
this.p = p;
}
public void setP (float[] p) {
this.p = p;
}
public float[] getP () {
return p;
}
public void setId (int id) {
this.id = id;
}
public int getId () {
return id;
}
public float summation () {
float sum = 0;
for (int i = 0; i < p.length; i++)
sum += p[i];
return sum;
}
public float miangin () {
return summation () / 4.0f;
}
#Override
public String toString () {
return new StringBuilder ()
.append ("Name: ").append (name)
.append (" Family name: ").append (fname)
.append (" Id: ").append (id)
.append (" min: ").append (miangin ())
.toString ();
}
}
And lastly, wherever your main method is, that is where you should get input from. Take note that when you make an array, each index is initialized to null so you still need to instantiate each array index before using. I made a sample below but you can modify it depending on what you need.
import java.util.*;
public class Exam {
Scanner sc;
Person[] people;
Exam () {
sc = new Scanner (System.in);
people = new Person[5];
}
public void getInput () {
for (int i = 0; i < people.length; i++) {
System.out.print ("Enter name: ");
String name = sc.nextLine ();
System.out.print ("Enter family name: ");
String fname = sc.nextLine ();
System.out.print ("Enter id: ");
int id = sc.nextInt (); sc.nextLine ();
System.out.println ("Enter points: ");
float[] points = new float[5];
for (int j = 0; j < points.length; j++) {
System.out.printf ("[%d] ", j + 1);
points[j] = sc.nextFloat (); sc.nextLine ();
}
people[i] = new Student (name, fname, id, points);
}
}
public void printInput () {
for (Person p: people)
System.out.println (p);
}
public void run () {
getInput ();
printInput ();
}
public static void main (String[] args) {
new Exam ().run ();
}
}
Just one last tip, if you ever need dynamic arrays in Java, check out ArrayList.
You can add a class attribute, and then add class information for each student, or you can add a class class, define an array of students in the class class, and add an add student attribute, and you can add students to that class.
First of all, please write class names with capital letter (Student, Exam <...>).
Exam class:
import java.util.Scanner;
public class Exam {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Student[] students = new Student[]{
new Student(),
new Student(),
new Student(),
new Student(),
new Student()
};
for (int i = 0; i < 5; i++) {
students[i].setFirstName();
students[i].setLastName();
students[i].setId();
}
}
}
Person class:
import java.util.Scanner;
public class Person {
String firstName, lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName() {
System.out.println("Type firstName: ");
this.firstName = new Scanner(System.in).next();
}
public String getLastName() {
return lastName;
}
public void setLastName() {
System.out.println("Type lastName: ");
this.lastName = new Scanner(System.in).next();
}
}
Student class:
import java.util.Scanner;
public class Student extends Person{
int id;
public int getId() {
return id;
}
public void setId() {
//Converting String line into Integer by Integer.parseInt(String s)
System.out.println("Type id: ");
this.id = Integer.parseInt(new Scanner(System.in).next());
}
}

Void-type not allowed here error [duplicate]

This question already has answers here:
What causes "'void' type not allowed here" error
(7 answers)
Closed 10 months ago.
I am trying to add these data I have read from a file into my map. My map is a treemap TreeMap<String, Student>, where Student in another class. I am trying to use the code map.put(formatSNumber, student.setCourses(courses)); to add the read file elements to my map, but I keep encountering that void type not allowed here error.
sNumber = Integer.parseInt(Breader.readLine());
formatSNumber = String.format("%03d", sNumber);
hours = Integer.parseInt(Breader.readLine());
grade = Double.parseDouble(Breader.readLine());
Student student = map.get(formatSNumber);
Course course = new Course(hours, grade);
List<Course> courses = student.getCourses();
courses.add(course);
map.put(formatSNumber, student.setCourses(courses));
end = Breader.ready();
Here is my full code:
import java.io.*;
import java.util.Scanner;
import java.util.TreeMap;
import java.util.Iterator;
import java.util.List;
public class FinalProgram {
public static void main(String[] args) throws IOException {
String nameFile = " ";
String classFile = " ";
TreeMap<String, Student> map = new TreeMap<>();
Scanner input = new Scanner(System.in);
try {
System.out.print("Enter the Name file(c:filename.txt): ");
nameFile = input.nextLine();
} catch(IllegalArgumentException e) {
System.out.printf("Invalid input. Please enter"
+ " filename in the form of "
+ "c:filename.txt\n", e.getMessage());
}
nameReader(nameFile, map);
try {
System.out.print("Enter the Class file(c:filename.txt): ");
classFile = input.nextLine();
} catch(IllegalArgumentException e) {
System.out.printf("Invalid input. Please enter"
+ " filename in the form of "
+ "c:filename.txt\n", e.getMessage());
}
classReader(classFile, map);
}
private static void nameReader(String file, TreeMap<String, Student> map)
throws IOException {
String nameFile = file;
int sNumber = 0;
String formatSNumber = " ";
String sName = " ";
//Instantiate FileReader and BufferedReader
FileReader freader = new FileReader(nameFile);
BufferedReader Breader = new BufferedReader(freader);
boolean end = Breader.ready();
do {
sNumber = Integer.parseInt(Breader.readLine());
formatSNumber = String.format("%03d", sNumber);
sName = Breader.readLine();
Student student = new Student(sName);
map.put(formatSNumber, student);
end = Breader.ready();
} while(end);
Iterator<String> keySetIterator = map.keySet().iterator();
while(keySetIterator.hasNext()) {
String key = keySetIterator.next();
System.out.println("key: " + key + " value: " + map.get(key).getName());
}
}
private static void classReader(String file, TreeMap<String, Student> map)
throws IOException {
String classFile = file;
int sNumber = 0;
String formatSNumber = " ";
int hours = 0;
double grade = 0.0;
double points = grade * hours;
double GPA = points / hours;
//Instantiate FileReader and BufferedReader
FileReader freader = new FileReader(classFile);
BufferedReader Breader = new BufferedReader(freader);
boolean end = Breader.ready();
do {
sNumber = Integer.parseInt(Breader.readLine());
formatSNumber = String.format("%03d", sNumber);
hours = Integer.parseInt(Breader.readLine());
grade = Double.parseDouble(Breader.readLine());
Student student = map.get(formatSNumber);
Course course = new Course(hours, grade);
List<Course> courses = student.getCourses();
courses.add(course);
map.put(formatSNumber, student.setCourses(courses));
end = Breader.ready();
} while(end);
points = grade * hours;
GPA = points / hours;
}
}
Student class:
import java.util.ArrayList;
import java.util.List;
public class Student {
private String name = " ";
private List<Course> courses = new ArrayList<>();
public Student(String name) {
this.name = name;
}
public Student(String name, List courses) {
this.name = name;
this.courses = courses;
}
public List getCourses() {
return courses;
}
public void setCourses(List courses) {
this.courses = courses;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Course class:
public class Course {
private int hours = 0;
private double grade = 0.0;
public Course(int hours, double grade) {
this.hours = hours;
this.grade = grade;
}
public void setHours(int hours) {
this.hours = hours;
}
public int getHours() {
return hours;
}
public void setGrade(double grade) {
this.grade = grade;
}
public double getGrade() {
return grade;
}
}
The second argument in map.put(formatSNumber, student.setCourses(courses)) must be of type Student. student.setCourses(courses) is a setter method with return type void, i.e. no return. This does not match.
You must have something like map.put("someString", new Student("name")) for instance, or map.put("someString", student) where student is of type Student.
The idea of put is about putting something into that Map.
More precisely, you typically provide (non-null) key and a value objects.
You are using student.setCourses(courses) as argument for that "value" parameter that put() expects.
That argument is an expression. And the result of that expression would be the result of the method call.
That method is defined to not return anything (void that is).
Obviously nothing is not the same as something. And that is what the compiler tries to tell you.
Two solutions:
pass a Student object
change that method setCourses()
Like this:
Student setCourses(... {
....
return this;
}
( you better go for option 1; 2 is more of a dirty hack, bad practice in essence )

Storing objects in an array, my values keep changing within my array

So I have a while loop which stores all of my variables, but my problem is that whenever the program loops it changes the values of the object in the previous array. So employeeArray is filled with all objects of the same values rather than storing the previous value and creating a new one. I am reading text from a .csv file. Can somebody please explain to me how to store my Employee objects without them changing each loop? Let me know if you need any clarification I know I probably missed some information somebody trying to help me may need. Anyways my code is below, I have 3 different classes but Im just going to put the Employee and EmpQuery class on here. I believe the problem is with my variables in the Employee class. PLEASE HELP ME, it would be greatly appreciated.
public class EmpQuery extends Employee {
public static void fillArrayObjects(Scanner s, Employee[] e){
//VARIABLES
String sNextLine;
int counter = 0;
int parsedString;
String employeeID;
String employeeName;
String employeeDepartment;
String employeeStartDate;
int employeeEarnings;
//DECLARE ARRAY TO HOLD EMPLOYEE OBJECTS
Employee employeeArray[] = new Employee [50];//50 records I believe
while(s.hasNext()){
//SCANNER AND SEPARATE STRING VALUE IN LINE
sNextLine = s.nextLine();
String[] tempSplit = sNextLine.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)", -1);
//REMOVE EVERYTHING EXPCEPT NUMBERS [4]
tempSplit[4] = tempSplit[4].replace(",","");
tempSplit[4] = tempSplit[4].replace("$","");
tempSplit[4] = tempSplit[4].replace("\"", "");
tempSplit[4] = tempSplit[4].replace(".00","");
parsedString = Integer.parseInt(tempSplit[4]);
//STORE TEMP SPLITS IN NEW VARIABLES
employeeID = tempSplit[0];
employeeName = tempSplit[1];
employeeDepartment = tempSplit[2];
employeeStartDate = tempSplit[3];
employeeEarnings = parsedString;
//CALLING FROM EMPLOYEE CLASS
Employee.enterData(employeeID, employeeName, employeeDepartment, employeeStartDate, employeeEarnings);
//STORE EACH NEW EMPLOYEE IN employeeArray
Employee i = new Employee(employeeID, employeeName, employeeDepartment, employeeStartDate, employeeEarnings);
employeeArray[counter] = i;
//TESTS
System.out.println(counter + " " + Employee.getEarnings(employeeArray[0]));//employee[1] keep changing every loop
//INCREMENT COUNTER
counter++;
}
System.out.println(Employee.getEarnings(employeeArray[12]));
System.out.println(Employee.getID(employeeArray[3]));
}
*************************************NEW CLASS******************************
package employeedb;
/**
*
* #author Daniel
*/
public class Employee {
//VARIABLES***************************************************************************************************
public String empID;
public String empName;
public String department;
public String startDate;
public int earnings;
Employee newGuys;
//EMPLOYEE*********************************************************************************************************
public Employee(){
empID = "";
empName = "";
department = "";
startDate = "";
earnings = 0;
}
public Employee(String iD, String name, String employeeDepartment, String startingDate, int salary){
empID = iD;
empName = name;
department = employeeDepartment;
startDate = startingDate;
earnings = salary;
}
public Employee(String iD, String name){
empID = iD;
empName = name;
}
//ENTER DATA*******************************************************************************************************
public void enterData(){
empID = "";
empName = "";
department = "";
startDate = "";
earnings = 0;
}
//ENTER DATA
public void enterData(String iD, String name){
empID = iD;
empName = name;
department = "";
startDate = "";
earnings = 0;
}
//ENTER DATA
public void enterData(String iD, String name, String employeeDepartment, String startingDate, int salary){
empID = iD;
empName = name;
department = employeeDepartment;
startDate = startingDate;
earnings = salary;
}
//VIEW SPECIFIC FIELD****************************************************************************************************
public void viewEmployeeID(Employee variable){
System.out.println(empID);
}
public void viewEmployeeName(Employee variable){
System.out.println(empName);
}
public void viewDepartment(Employee variable){
System.out.println(department);
}
public void viewStartDate(Employee variable){
System.out.println(startDate);
}
public void viewEarnings(Employee variable){
System.out.println(earnings);
}
//VIEW DATA**********************************************************************************************************
public void viewAllData(){
empID = "";
empName = "";
department = "";
startDate = "";
earnings = 0;
System.out.println("Employee ID: " + empID);
System.out.println("Employee name: " + empName);
System.out.println("Employee department: " + department);
System.out.println("Employee start date: " + startDate);
System.out.println("Employee earnings: $" + earnings);
System.out.println("");
}
//VIEW DATA
public void viewData(String iD, String name, String employeeDepartment, String startingDate, int salary){
empID = iD;
empName = name;
department = employeeDepartment;
startDate = startingDate;
earnings = salary;
System.out.println("Employee ID: " + empID);
System.out.println("Employee name: " + empName);
System.out.println("Employee department: " + department);
System.out.println("Employee start date: " + startDate);
System.out.println("Employee earnings: $" + earnings);
System.out.println("");
}
//RETURN DATA*********************************************************************************************************
//GET ID
public String getID(Employee variable){//void
return empID;
}
//GET NAME
public String getName(Employee variable){
return empName;
}
//GET DEPARTMENT
public String getDepartment(Employee variable){
return department;
}
//GET START DATE
public String getStartDate(Employee Variable){
return startDate;
}
//GET EARNINGS
public int getEarnings(Employee Variable){
return earnings;
}
}
The main problem is that you set the variables in Employee as static, that means they are shared in every instance of the class.
They should not be static so every object has their own.

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

When I try to print a collection object, it prints Employee#122392Iie92. Why is it printing this and not the details of the employee list?
My code:
public class Employee {
private String name;
private String designation;
private int employeeId;
private int salary;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public int getEmployeeId() {
return employeeId;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}
import java.util.ArrayList;
import java.util.Scanner;
public class EmployeeManagement {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList <Employee> lst = new ArrayList <Employee> ();
System.out.println("Enter the number of employees : ");
int num = sc.nextInt();
EmployeeManagement emp = new EmployeeManagement();
emp.addEmployeeName( num, lst);
}
public void addEmployeeName(int num,ArrayList<Employee> lst) {
Employee em = new Employee();
for(int i =0; i<num ; i++)
{
System.out.println("Enter the employee id : ");
em.setEmployeeId(sc.nextInt());
System.out.println("Enter the name of employee : ");
em.setName(sc.next());
System.out.println("Enter the designation of employee : ");
em.setDesignation(sc.next());
System.out.println("Enter the Salary of employees : ");
em.setSalary(sc.nextInt());
lst.add(em);
}
System.out.println(lst);
}
}
It is printing using the default toString method of the Object class. You need to override toString in the Employee class if you want to show values. It is currently showing the class name and hashcode.
Write a toString method like this in Employee:
#Override
public String toString(){
SubString sb = new SubString();
sb.append("Name :- ")append(name).append(id); //all relevant fields
return sb.toString();
}
Move new statement inside loop else you are adding and updating same object again and again.
public void addEmployeeName(int num,ArrayList<Employee> lst) {
for(int i =0; i<num ; i++)
{
Employee em = new Employee();
System.out.println("Enter the employee id : ");
em.setEmployeeId(sc.nextInt());
System.out.println("Enter the name of employee : ");
em.setName(sc.next());
System.out.println("Enter the designation of employee : ");
em.setDesignation(sc.next());
System.out.println("Enter the Salary of employees : ");
em.setSalary(sc.nextInt());
lst.add(em);
}
System.out.println(lst);
}
}

Categories