Creating an ArrayList of Employees - java

I have three classes
employee
production workers
shift supervisor class
My idea is to make production and shift supervisor extend the employee class and then create another class, EmployeeList to fill it with information about production workers and shift supervisors.
How can i get the names and info from employee class to iterate into an arraylist?
How can i add a random list of employees more than half being prod. workers and the rest shift supervisors?
Employee:
public class Employee {
public String EmployeeName;
public String EmployeeNumber;
public int hireyear;
public double WeeklyEarning;
public Employee()
{
EmployeeName = null;
EmployeeNumber = null;
hireyear = 0;
WeeklyEarning = 0;
}
public static final String[] Enum = new String[] {
"0001-A", "0002-B","0003-C","0004-D","0002-A",
"0003-B","0004-C","0005-D","0011-A", "0012-B",
"0013-C","0014-D","0121-A", "0122-B","0123-C" };
public static final String[] Ename = new String[] {
"Josh", "Alex", "Paul", "Jimmy", "Josh", "Gordan", "Neil", "Bob",
"Shiv", "James", "Jay", "Chris", "Michael", "Andrew", "Stuart"};
public String getEmployeeName()
{
return this.EmployeeName;
}
public String getEmployeeNumber()
{
return this.EmployeeNumber;
}
public int gethireyear()
{
return this.hireyear;
}
public double getWeeklyEarning()
{
return this.WeeklyEarning;
}
public String setEmployeeName(String EName)
{
return this.EmployeeName = EName;
}
public String setEmployeeNumber(String ENumber)
{
return this.EmployeeNumber = ENumber;
}
public int setEmployeehireyear(int Ehireyear)
{
return this.hireyear = Ehireyear;
}
public double setEmployeeweeklyearning(double Eweeklyearning)
{
return this.WeeklyEarning = Eweeklyearning;
}
}
ProductionWorker:
import java.util.Random;
public class ProductionWorker extends Employee {
public double HourlyRate;
public ProductionWorker()
{
super();
HourlyRate = 0;
}
public static void main(String[] args) {
ProductionWorker pw = new ProductionWorker();
Random rnd = new Random();
int count =0;
// adding random Employees.....
while(count<5)
{
int num= rnd.nextInt(Enum.length);
int decimal = rnd.nextInt(10);
double dec = decimal/10;
pw.setEmployeeName(Ename[num]);
pw.setEmployeeNumber(Enum[num]);
pw.setEmployeehireyear(rnd.nextInt(35) + 1980);
pw.setEmployeeweeklyearning(rnd.nextInt(5000) + 5000);
pw.setHourlyRate(rnd.nextInt(44) + 6 + dec);
System.out.println("EmployeeName: " + pw.getEmployeeName() + "\nEmployeeNumber: " + pw.getEmployeeNumber() +
"\nHireYear: " + pw.gethireyear() + "\nWeeklyEarning: " + pw.getWeeklyEarning() +
"\nHourlyRate: " + pw.getHourlyRate() +"\n");
count++;
}
}
public double getHourlyRate()
{
return this.HourlyRate;
}
public void setHourlyRate(double hourlyrate)
{
this.HourlyRate = hourlyrate;
}
}
ShiftSupervisor:
import java.util.Random;
public class ShiftSupervisor extends Employee{
public double YearlySalary;
public int GoalsCleared;
public ShiftSupervisor()
{
super();
YearlySalary = 0;
}
public static void main(String[] args) {
ShiftSupervisor S = new ShiftSupervisor();
Random rnd = new Random();
int count =0;
// adding random Employees.....
System.out.println("Adding Employees..");
while(count<5)
{
int num= rnd.nextInt(Enum.length);
S.setEmployeeName(Ename[num]);
S.setEmployeeNumber(Enum[num]);
S.setEmployeehireyear(rnd.nextInt(35) + 1980);
S.setEmployeeweeklyearning(rnd.nextInt(100) * 100);
S.setYearlySalary(rnd.nextInt(40000) + 40000);
System.out.println("EmployeeName:" + S.getEmployeeName() + "\nEmployeeNumber: " + S.getEmployeeNumber() +
"\nHireYear: " + S.gethireyear() + "\nWeeklyEarning: " + S.getWeeklyEarning() +
"\nearlySalary: " + S.getYearlySalary() +"\n");
count++;
}
}
// returns yearly salary
public double getYearlySalary()
{
return this.YearlySalary;
}
// returns goals cleared
public int getGoalsCleared()
{
return this.GoalsCleared;
}
// set yearly salary
public void setYearlySalary(double yearlysalary)
{
this.YearlySalary = yearlysalary;
}
}

The first thing I would do is have all necessary fields set in the constructor. If an Employee doesn't "exist" until it has a name, then that should be part of the constructor.
Then, I would suggest you consider renaming some of your fields. When I first saw Enum as a String[] and highlighted as a type, it took me a moment to figure out what exactly was going on. Renaming it to employeeNumbers could solve this.
Next, I think you should have an EmployeeGenerator class whose sole purpose is generating Employees.
public class EmployeeGenerator {
public ProductionWorker generateProductionWorker() {
Random rng = new Random();
int numberOfEmployeeNames = employeeNames.length;
String employeeName = employeeNames[rng.nextInt(numberOfEmployeeNames)];
int numberOfEmployeeNumbers = employeeNumbers.length;
String employeeNumber = employeeNumbers[rng.nextInt(numberOfEmployeeNumbers)];
ProductionWorker worker = new ProductionWorker(employeeName, employeeNumber);
int yearHired = rng.nextInt(100) + 1900;
worker.setHireYear(yearHired);
int hourlyRate = rng.nextInt(20) + 10;
worker.setHourlyRate(hourlyRate);
// any other fields...
return worker;
}
// method to generate shift supervisor
}
And then you can simply do
public static void main(String[] args) {
Random rng = new Random();
int numberOfEmployeesToGenerate = 1000;
int minimumNumberOfProductionWorkers = numberOfEmployeesToGenerate / 2;
int numberOfProductionWorkersToGenerate =
minimumNumberOfProductionWorkers + rng.nextInt(100);
int numberOfSupervisorsToGenerator =
numberOfEmployeesToGenerate - numberOfProductionWorkersToGenerate;
List<Employee> employees = new ArrayList<>();
EmployeeGenerator generator = new EmployeeGenerator();
for (int i = 0; i < numberOfProductionWorkersToGenerate; i++) {
ProductionWorker worker = generator.generateProductionWorker();
employees.add(worker);
}
for (int i = 0; i < numberOfSupervisorsToGenerate; i++) {
Supervisor supervisor = generator.generateSupervisor();
employees.add(supervisor);
}
}
This should hopefully give you a point in the right direction. This isn't perfect code, and there are other ways to refactor this to make it more maintainable and performant.

When you say you want to add a random list of employees, What do you mean exactly?
Currently you instantiate only one ProductionWorker and one ShiftSupervisor, change the values of the member variables, and print some text to StdOut.
Do you want to store instances in a list or is the console output sufficient?
Also, you have two main-methods. Which one will be performed? It might be better to have one Main class as an entry point for your application and from there create the instances.
In general you can do something like that:
public class Main {
public static void main(String[] args) {
List<Employee> emps = new ArrayList<>();
for (int i = 0; i < 5; i++) {
//create new employee
emps.add(newEmployee);
}
//do something with list
}
}

Related

using loop variables with object variables

This is what i got
Constructor:
public class Assignment08_ {
String name;
String abrv;
int atomicNumber;
double atomicMass;
int group;
int period;
public Assignment08_(String name, String abrv, int atomicNumber, double
atomicMass, int group, int period) {
this.name = name;
this.abrv = abrv;
this.atomicNumber = atomicNumber;
this.atomicMass = atomicMass;
this.group = group;
this.period = period;
}
}
And the Class:
import java.io.File;
import java.util.Scanner;
public class Assignment08 {
public static void main(String[] args) throws Exception {
Assignment08_[] elementArr = new Assignment08_[119];
reader(elementArr);
for(int i = 0; i < args.length; i++) {
action(elementArr, args[i]);
}
}
public static void reader(Assignment08_[] elements) throws Exception {
Scanner data = new Scanner(new File("/srv/datasets/elements"));
while (data.hasNext()) {
int atomicNumber = data.nextInt();
String abrv = data.next();
String name = data.next();
double atomicMass = data.nextDouble();
int period = data.nextInt();
int group = data.nextInt();
elements[atomicNumber] = new Assignment08_(name, abrv, atomicNumber,
atomicMass, group, period);
}
data.close();
}
public static void action(Assignment08_[] element, String str) {
// for testing
System.out.printf("%s%n", element[4].abrv);
for (int i = 0; i < 119; i++) {
if (str.compareTo(element[i].abrv) == 0)
System.out.println(element[i].name);
}
}
}
i input "java Assignment08_ H" (which is equal to element[0].abrv)
i get the output:
"
Be
Exception in thread "main" java.lang.NullPointerException
at Assignment08.action(Assignment08.java:33)\
at Assignment08.main(Assignment08.java:11)
"
Be = element[4].abrv
and its wierd because if i were to take away that for statement and leave only the nested if statement and change the i to a Number (like 0), it will print the name and run properly( if i input H which equals element[0].abrv), soooo i dont know what going on here, any help would be great, thx

Issue recalling method. unsure of where im going wrong

Below is my code and I have notes beside where my errors are showing. Im unsure where I am going wrong when recalling my method or if that is even the issue.
import java.util.Scanner;
public class HurlerUse
{
static Hurler[] hurlerArray;
// find lowest score (static method)
public static int findLow(Hurler[] hurlerArray)
{
for(int i = 0; i < hurlerArray.length; i++)
{
int lowest = 0;
int index = 0;
for(int j=0; j<hurlerArray.length; j++)
{
int current = hurlerArray[i].totalPoints();// issue with my method 'totalPoints'
if(current < lowest)
{
lowest = current;
index = i;
}
}
return index;
}
}
//main code
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
Hurler[] hurlerArray = new Hurler[5];
for (int i = 0; i <4; i++)
{
hurlerArray[i] = new Hurler();
System.out.println ("Enter Hurler Name:");
hurlerArray[i].setName(sc.nextLine());
hurlerArray[i].setGoalsScored(sc.nextInt());
System.out.println("Enter the hurler's goals scored");
hurlerArray[i].setPointsScored(sc.nextInt());
System.out.println("Enter the hurler's points scored");
}
for(int i=0;i< hurlerArray.length; i++)
{
hurlerArray[i] = new Hurler(MyName, MyGoalsScored, MyPointsScored);// issue with all 3 objects in the brackets but im unsure of how to fix them
}
System.out.println("The lowest scoring hurler was " + hurlerArray[findLow(hurlerArray)].getName());// error with my code here I think it is in the method
}
}//end of class
I know the nyName, myGoalsScored, myPointsScored is incorrect but can anyone explain why?
This is the class page that accompanies it
public class Hurler
{
private String name;
private int goalsScored;
private int pointsScored;
public Hurler() //constructor default
{
name ="";
goalsScored = 0;
pointsScored = 0;
}
public Hurler(String myName, int myGoalsScored, int myPointsScored) // specific constructor
{
name = myName;
goalsScored = myGoalsScored;
pointsScored = myPointsScored;
}
//get and set name
public String getMyName()
{
return name;
}
public void setName(String myName)
{
name = myName;
}
//get and set goals scored
public int getGoalsScored()
{
return goalsScored;
}
public void setGoalsScored(int myGoalsScored)
{
goalsScored = myGoalsScored;
}
// get and set points scored
public int getPointsScored()
{
return pointsScored;
}
public void setPointsScored(int myPointsScored)
{
pointsScored = myPointsScored;
}
public int totalPoints(int myGoalsScored, int myPointsScored)
{
int oneGoal = 3;
int onePoint = 1;
int totalPoints = ((goalsScored * oneGoal) + (pointsScored * onePoint));
{
return totalPoints;
}
}
}//end of class
You call totalPoints() without parameters while method totalPoints(int, int) in Hurler class expects two int parameters.
Objects MyName, MyGoalsScored, MyPointsScored are not declared at all.
You call getName() method, while in Hurler class you do not have one. There is method getMyName(), maybe you want to call that one.

Java Class - main not compiling when i read to departments

I wrote the two departments and when I try to read to the class from the chief and I have a problem compiling and I can not understand what the problem is, I'd love to help.
in main the error is on the line : 5.
Main:
public class main {
public static void main(String[]args){
Lecturer LecturerObject = new Lecturer("Dani",3,"Banana",1001);
The error is here >>Lecturer[] L1 = new Lecturer("Dani",2,"Banana",1001);
College FirstCollege = new College("Hmpson",2, L1);
}
}
First Class:
public class Lecturer {
public String nameOfLecturer = "";
public int numOfTimesPenFalls = 0;
public String favoriteIceCream = "";
public int numAuto = 1000;
//constructors, same name like class
public Lecturer(String name, int TimesPenFalls, String IceCream,
int num) {
nameOfLecturer = name;
numOfTimesPenFalls = TimesPenFalls;
favoriteIceCream = IceCream;
numAuto = num;
int maxLecturer=10;
}
//Copy constructor
public Lecturer(Lecturer other){
nameOfLecturer = other.nameOfLecturer;
numOfTimesPenFalls = other.numOfTimesPenFalls;
favoriteIceCream = other.favoriteIceCream;
numAuto = other.numAuto;
}
}
Secoand Class:
public class College {
public String CollegeName = "";
public int numOfLecturers = 0;
public Lecturer[] allLecturers;
// constructors, same name like class
public College(String name, int numLecturers, Lecturer[] dataBase) {
CollegeName = name;
numOfLecturers = numLecturers;
allLecturers = dataBase;
int maxLecturer = 10;
}
// getter, only private
public String getCollegeName() {
return CollegeName;
}
// setter, only private
public void setCollegeName(String newcollegeName) {
CollegeName = newcollegeName;
}
public boolean newLecturer(Lecturer addNewLecturer, int maxLecturer) {
if (numOfLecturers < maxLecturer || numOfLecturers == maxLecturer) {
numOfLecturers += 1;
return true;
} else {
System.out.print("Sorry, Max Lecturer!");
return false;
}
}
public void sortLecturer(Lecturer[] arrAllLecturers) {
int numOfTimesPenFalls = 0;
}
}
I'm first started with java I would be happy for a detailed explanation where is the problem, thank you very much.
This statement here
Lecturer[] L1 = new Lecturer("Dani",2,"Banana",1001); is wrong because you have defined L1 as an array but you are initializing it as a simple Object....
in some IDEs like eclipse, the compiler will complain with a message like
Type mismatch: cannot convert from Lecturer to Lecturer[]
Ergo: you need to init L1 as it is, as an array:
do this:
Lecturer[] L1 = new Lecturer[]{new Lecturer("Dani",2,"Banana",1001)};
now you have an array with one Lecturer object inside..
You are trying to assign array Lecture object to array, which can be done in following manner correctly.
Lecturer[] L1 = new Lecturer[] {new Lecturer("Dani",2,"Banana",1001)};

Java testing out a driver class

I've been having some issues with this program. I have to test out using a driver class each method, but I can't seem to understand what I should do when the parameters are strings.
I had an example for int parameters but the example never showed anything on string parameters and how to convert. Using null makes my driver class run but putting an int or string won't.
What can I do to convert this correctly, so it can display whatever I have in the no parameter constructor?
public class StudentListing
{
private String name;
private String number;
public StudentListing(String n, String num)
{
name = n;
number = num;
}
public StudentListing()
{
name = null;
number = null;
}
public String toString()
{
return("Name is " + name +
"\nNumber is " + number + "\n");
}
public void show()
{
System.out.println(toString());
}
public StudentListing Clone()
{
StudentListing clone = new StudentListing (name, number);
return clone;
}
public int compareTo(String targetKey)
{
return (name.compareTo(targetKey));
}
public void input()
{
name = JOptionPane.showInputDialog("Enter a name");
number = JOptionPane.showInputDialog("Enter a number");
}// end of StudentListing
}//end of class
public class StudentListingDriver
{
public static void main(String[] args)
{
StudentListing s1 = new StudentListing();
StudentListing s2 = new StudentListing(null,null);
System.out.println(s1);
s1.input();
StudentListing s3 = s2.clone();
s1.show();
}
}
You can have default values and make the no-args constructor call the other constructor.
Use Integer.parseInt(); to convert from a String to an Integer.
You also need to check the conversion for exceptions.
Like this:
public class StudentListing {
private String name;
private int number;
public StudentListing(String n, int num) {
name = n;
number = num;
}
public StudentListing() {
this("defaultName", 0);
}
public String toString() {
return ("Name is " + name + "\nNumber is " + number + "\n");
}
public void show() {
System.out.println(toString());
}
public StudentListing Clone() {
StudentListing clone = new StudentListing(name, number);
return clone;
}
public int compareTo(String targetKey) {
return (name.compareTo(targetKey));
}
public void input() {
name = JOptionPane.showInputDialog("Enter a name");
number = Integer
.parseInt(JOptionPane.showInputDialog("Enter a number"));
}
}
The tester:
public class StudentListingDriver {
public static void main(String[] args) {
StudentListing s1 = new StudentListing();
StudentListing s2 = new StudentListing(null, 0);
System.out.println(s1);
s1.input();
StudentListing s3 = s2.Clone();
s1.show();
}
}

Calculate total from array

Two questions:
1. How do I create a method called getTotal() that traverses through the array and counts the total of the votes for all Candidates?
2. Where and how to create the method printResults() , that should transverse through the array and creates a table with columns for Candidate name, followed by votes received, and then percentage of total votes
Candidate
public class Candidate
{
// instance variables
private int numVotes;
private String name;
/**
* Constructor for objects of class InventoryItem
*/
public Candidate(String n, int v)
{
// initialise instance variables
name = n;
numVotes = v;
}
public int votes()
{
return numVotes;
}
public void setVotes(int num)
{
numVotes = num;
}
public String getName()
{
return name;
}
public void setName(String n)
{
name = n;
}
public String toString()
{
return name + " received " + numVotes + " votes.";
}
public int getTotal(Candidate[] election)
{
}
}
TestCandidate
public class TestCandidate
{
public static void printVotes(Candidate[] election)
{
for(int i = 0; i < election.length; i++)
System.out.println(election[i]);
}
public int getTotal(Candidate[] election)
{
int total = 0;
for(Candidate candidate : election )
{
total += candidate.numVotes;
}
return total;
}
public static void main(String[] args)
{
Candidate[] election = new Candidate[5];
// create election
election[0] = new Candidate("John Smith", 5000);
election[1] = new Candidate("Mary Miller", 4000);
election[2] = new Candidate("Michael Duffy", 6000);
election[3] = new Candidate("Tim Robinson", 2500);
election[4] = new Candidate("Joe Ashtony", 1800);
System.out.println(" Results per candidate ");
System.out.println("______________________________");
System.out.println();
printVotes(election);
System.out.println("The total of votes in election: " + getTotal() );
}
}
public int getTotal(Candidate[] election)
{
int total = 0;
for( Candidate candidate : election ) {
total += candidate.votes();
}
return total;
}
This method and printResults() method in my opinion should go to some wrapper class that gathers all Candidates. For example like this:
class CandidatesList {
private Candidate[] candidates;
public CandidatesList(Candidate[] candidates) {
this.candidates = candidates;
}
public int getTotal()
{
int total = 0;
for( Candidate candidate : candidates) {
total += candidate.votes();
}
return total;
}
public String toString() {
StringBuilder builder = new StringBuilder();
int total = getTotal();
for( Candidate candidate : candidates) {
builder.append( String.format( "%20s | %5d | %.2f %%\n",
candidate.getName(), candidate.votes(), candidate.votes() / total );
}
return builder.toString();
}
}
You can use it like this:
CandidatesList list = new CandidatesList(election);
System.out.print(list);
System.out.format("Total votes: %d\n", list.getTotal());

Categories

Resources