I'm learning object-oriented programming in a Java course, and I'm doing a project where a program creates three types of objects: Address, Date, and Employee. The program stores data of several employees and then displays the data in an array of type Employee.
I'm using four different classes: an Address class, a Date class, and an Employee Class, and an EmployeeTest class that creates the array.
Here is the Address class:
public class Address {
private String Street;
private String City;
private String State;
private int ZipCode;
public Address(String St, String Ci, String Sta, int Zip){
Street = St;
City = Ci;
State = Sta;
ZipCode = Zip;
}
public String getEmployeeAddress(){
return (Street + ", " + City + ", " + State + " " + ZipCode);
}
}
The Date Class:
public class Date {
private int Month;
private int Day;
private int Year;
public Date(int M, int D, int Y){
Month = M;
Day = D;
Year = Y;
}
public String getDateString(){
return (Month + "/" + Day + "/" + Year);
}
}
And, the Employee Class:
public class Employee {
private int EmployeeNum;
public void setEmployeeNum(int ENum){
EmployeeNum = ENum;
}
public int getNum(){
return EmployeeNum;
}
public String getDate(){
return Date.getDateString();
}
public String getName(){
return Name.getEmployeeName();
}
public String getAddress(){
return Address.getEmployeeAddress();
}
}
All of these classes are in the same package (I'm using Eclipse). The point of the Employee class is to create an object of type Employee and be able to get it's Address, Name, and HireDate using the Address, Name, and Date classes.
The place where the array comes into play is here:
import java.util.Scanner;
import java.lang.*;
public class EmployeeTest {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("How many employees will have their data stored today?");
int EmployeeAmount = Integer.parseInt(input.nextLine());
Employee [] EmployeeArray = new Employee[EmployeeAmount];
for (int i = 0; i < EmployeeArray.length; i ++){
System.out.print("What is employee " + (i+1) + "'s employee number?");
int EmployeeNumber = Integer.parseInt(input.nextLine());
EmployeeArray[i] = new Employee();
EmployeeArray[i].setEmployeeNum(EmployeeNumber);
System.out.println("What is the first name of employee " + EmployeeNumber + "?");
String EmployeeFirstName = input.nextLine();
System.out.println("What is the last name of employee " + EmployeeNumber + "?");
String EmployeeLastName = input.nextLine();
Name EmployeeName = new Name(EmployeeFirstName, EmployeeLastName);
System.out.println("Please enter the street address: ");
String StreetAddress = input.nextLine();
System.out.println("Please enter the name of the city: ");
String CityName = input.nextLine();
System.out.println("Please enter the two character code for the state: ");
String StateID = input.nextLine();
System.out.println("Please enter this address's zip code: ");
int ZipCode = Integer.parseInt(input.nextLine());
Address EmployeeAddress = new Address(StreetAddress, CityName, StateID, ZipCode);
System.out.println("Finally, what was the month(#) of the hire date?");
int Month = Integer.parseInt(input.nextLine());
System.out.println("What was the day(#)?");
int Day = Integer.parseInt(input.nextLine());
System.out.println("What was the year?");
int Year = Integer.parseInt(input.nextLine());
Date HireDate = new Date(Month, Day, Year);
}
for (int j = 0; j < EmployeeArray.length; j ++){
System.out.println("Employee number: " + EmployeeArray[j].getNum());
System.out.println("Employee Name: " + EmployeeArray[j].getName());
System.out.println("Employee Address: " + EmployeeArray[j].getAddress());
System.out.println("Employee Hiredate: " + EmployeeArray[j].getDate());
}
}
}
The program prompts the user for the number of employees to be stored in the array, then creates an Employee[] of size EmployeeAmount. The idea of the code is that for each Employee in the Array, all of the variables in the other classes are obtained: Employee Number, Employee Name (first and last), Address (Street Address, City, State Code, Zip Code), Hire Date (Month, Day, Year). After all this is obtained, the second for loop iterates through each Employee and displays the info.
The problem I am having is that in the Employeeclass, Eclipse gives me an error in the getDate(), getName(), and getAddress() methods. When I say for example, return Date.getDateString(), Eclipse says that I cannot make a static reference to a non-static method. It's solution is to make getDateString() static, and I tried this, but the problem is that by making all the methods and variables in the Address, Employee, and Date classes, the values are locked. Meaning that the same data will be displayed for all employees.
Here's what I mean. Below is a sample output if I made all the methods and variables static. The text in between the asterisks is what the user inputs.
How many employees will have their data stored today?**2**
What is employee 1's employee number?**1**
What is the first name of employee 1?
**Bob**
What is the last name of employee 1?
**Jones**
Please enter the street address:
**300 1st Avenue**
Please enter the name of the city:
**New York**
Please enter the two character code for the state:
**NY**
Please enter this address's zip code:
**10001**
Finally, what was the month(#) of the hire date?
**1**
What was the day(#)?
**1**
What was the year?
**2001**
What is employee 2's employee number?**2**
What is the first name of employee 2?
**Bobby**
What is the last name of employee 2?
**Robinson**
Please enter the street address:
**301 1st Avenue**
Please enter the name of the city:
**Los Angeles**
Please enter the two character code for the state:
**CA**
Please enter this address's zip code:
**90001**
Finally, what was the month(#) of the hire date?
**1**
What was the day(#)?
**2**
What was the year?
**2004**
Employee number: 2
Employee Name: Bobby Robinson
Employee Address: 301 1st Avenue, Los Angeles, CA 90001
Employee Hiredate: 1/2/2004
Employee number: 2
Employee Name: Bobby Robinson
Employee Address: 301 1st Avenue, Los Angeles, CA 90001
Employee Hiredate: 1/2/2004
By making all of the variables and methods static, the values are locked as shown, which makes the program useless. Does anyone have a solution to this problem? I need a way to display the information of each employee while referencing the methods in the other classes. Now, normally I would just create all the variables and methods under one class called Employee, but the assignment instructions specify that I need to make individual classes.
You are creating a Name, Address, and Date for each iteration of the for loop. But you have not way, nor do you set them on each Employee instance.
You need to add methods to set the values on each Employee and store the information. Something like this:
public class Employee {
private int employeeNum;
private Name name;
private Date hireDate;
private Address address;
public void setEmployeeNum(int eNum){
employeeNum = eNum;
}
public int getEmployeeNum(){
return employeeNum;
}
public void setHireDate(Date date){
this.hireDate = date;
}
public String getHireDate(){
return hireDate.getDateString();
}
public void setName(Name n){
this.name = n;
}
public String getName(){
return name.getEmployeeName();
}
public void setAddress(Address addy){
this.address = addy;
}
public String getAddress(){
return address.getEmployeeAddress();
}
}
Then in your for loop, set the values:
EmployeeArray[i].setName(EmployeeName);
EmployeeArray[i].setAddress(EmployeeAddress);
EmployeeArray[i].setHireDate(HireDate);
By the way, you should not capitalize variables, only classes.
Variables should be camel-cased.
Related
We have to use set and get methods to such as
Employee()
Employee(empId:int)
Employee(empId:int, payRate:double, weeklyHrs:double)
setId(empId:int):void
setPayRate(payRate:double):void
setHrs(weeklyHrs:double):void
getId():int
getPayRate():double
getHrs():double
getWeeklyPay():double
toString():String
to create an employee class and employee class demo. We have to use two employee id's and type in their weekly hours and pay to return how much they made. Here is what I have down for the Employee class:
//#param
Scanner input = new Scanner(System.in); //Scanner object
public void setID(int empID){
System.out.println("Enter employee 1's id: ");
String input2 = input.next();
int emp1 = Integer.parseInt(input2);
System.out.println("Enter employee 2's id: ");
String input3 = input.next();
int emp2 = Integer.parseInt(input3);
}
//#param
public void setPayRate(double payRate){
System.out.println("Enter employee 1's payrate: ");
String input4 = input.next();
double pay1 = Double.parseDouble(input4);
System.out.println("Enter employee 2's payrate: ");
String input5 = input.next();
double pay2 = Double.parseDouble(input5);
}
//#param
public void setHrs(double weeklyHrs){
System.out.println("Enter employee 1's hours: ");
String input6 = input.next();
double hour1 = Double.parseDouble(input6);
System.out.println("Enter employee 2's hours: ");
String input7 = input.next();
double hour2 = Double.parseDouble(input7);
}
//GET METHODS
public int getID(int empID){
return empID;
}
public double getHrs(double hours){
return hours;
}
public double getWeeklyPay(double pay){
return pay;
}
//DISPLAY ANSWERS
public String toString(int emp1,int emp2,double hour1,double hour2,double pay1,double pay2){
String myString= String.format("The first employee's ID is: " + emp1 +
"The second employee's ID is: " + emp2 +
"The first employee's hours are: " + hour1 +
"The secondemployee's hours are: " + hour2 +
"The first employee's pay: $%,.2f"+ pay1*hour1 +
"The second employee's pay: $%,.2f" + pay2*hour2,
emp1,emp2,hour1,hour2,pay1,pay2);
return myString;
}
}//End of class
I'm just wondering what I would put in my Employee Class Demo so that it would be able to return the toString method?
System.out.println() calls the toString() method automatically on any object you pass into it - alternatively, you can just call it yourself:
Employee e;
// properly initialize e
System.out.println(e); // works
System.out.println(e.toString()); // also works
As a side note, your toString() method is incorrect. It should be a member function of the Employee class - making it a method that takes Employee objects is the wrong way to do it (assuming you want to follow standard Java OOP practices).
The proper method would look something like this:
// Notice no arguments are passed in
public String toString() {
// Instead, we use the "this" variable
return String.format("My ID is %s, my hours are %f, and my pay is $%,.2f", this.empID, this.hours, this.pay);
}
Please excuse what is probably a very basic question, but I am writing a program to store employee info and it works fine until it tries to set the info inside my employee class. It gives a stackoverflow error and I cannot figure out why. Thanks for any help.
Main class:
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner Input = new Scanner(System.in);
System.out.println("Enter the number of employees to enter.");
int employeeCount = Input.nextInt();
Input.nextLine();
Employee employee[] = new Employee[employeeCount];
String namesTemp;
String streetTemp;
String cityTemp;
String stateTemp;
String zipCodeTemp;
String address;
String dateOfHireTemp;
for(int x = 0; x < employeeCount; x++)
{
System.out.println("Please enter the name of Employee " + (x + 1));
namesTemp = Input.nextLine();
System.out.println("Please enter the street for Employee " + (x + 1));
streetTemp = Input.nextLine();
System.out.println("Please enter the city of Employee " + (x + 1));
cityTemp = Input.nextLine();
System.out.println("Please enter the state of Employee " + (x + 1));
stateTemp = Input.nextLine();
System.out.println("Please enter the zip code of Employee " + (x + 1));
zipCodeTemp = Input.nextLine();
address = streetTemp + ", " + cityTemp + ", " + stateTemp + ", " + zipCodeTemp;
System.out.println("Please enter the date of hire for Employee " + (x + 1));
dateOfHireTemp = Input.nextLine();
System.out.println("The employee ID for employee " + (x + 1) + " is " + (x + 1));
employee[x] = new Employee(x, namesTemp, address, dateOfHireTemp);
}
}
}
Employee class:
public class Employee
{
private int employeeID;
private Name name;
private Address address;
private DateOfHire hireDate;
public Employee()
{
}
public Employee(int employeeID, String name, String address, String hireDate)
{
String temp;
Name employeeName = new Name(name);
this.employeeID = employeeID;
}
}
Name class:
public class Name
{
public Name name;
public Name(String name)
{
Name employeeName = new Name(name);
this.name = employeeName;
}
}
The most common cause of StackoverflowExceptions is to unknowingly have recursion, and is that happening here? ...
public Name(String name)
{
Name employeeName = new Name(name); // **** YIKES!! ***
this.name = employeeName;
}
Bingo: recursion!
This constructor will create a new Name object whose constructor will create a new Name object whose constructor will... and thus you will keep creating new Name objects ad infinitum or until stack memory runs out. Solution: don't do this. Assign name to a String:
class Name {
String name; // ***** String field!
public Name(String name)
{
this.name = name; // this.name is a String field
}
Typically a class is used to group data together with functionality. It appears that the Name class is simply a wrapper for a String without adding any functionality. At this point in your Java career, it is probably better to declare String name; in the Employee class and remove the Name class all together. (Note that this would remove the error from your code that Hovercraft Full of Eels described.)
i am currently using inheritance and as you can see below, i have two classes, the person and the passenger. In the person i have the main toString() method and in the passenger i call a super.toString() and add the new info, priority booking/noOfBags and the ID. The problem i have is, when the user adds a new passenger to the array, when you print the array the data isn't in the same format as entered. I am pretty sure that i have called everything correctly and im not 100% sure why just the name aspect of the toString messes up (notice that the DOB/ID/noOfBags and priority booking all formatted correctly). If anyone can point me as to why just the name is printing incorrectly it would be greatly appreciated.
Code
This is the constructor in the main class Person
public Person()
{
name = new Name();
dateOfBirth = new Date();
}
public Person(String titleIn, String firstNameIn, String surNameIn, int day, int month, int year)
{
name = new Name(titleIn, firstNameIn, surNameIn);
dateOfBirth = new Date(day, month, year);
}
Here is the method i use to get the Name and DOB details of the new passenger
public void read()
{
try
{
Scanner kbInt = new Scanner(System.in);
Scanner kbString = new Scanner(System.in);
System.out.println("***Passenger Details: ***");
System.out.print("Title : ");titleRead=kbInt.nextLine();
System.out.print("First Name : ");FNameRead=kbString.nextLine();
System.out.print("Surname : ");SNameRead=kbString.nextLine();
name = new Name(titleRead, FNameRead, SNameRead);
System.out.println("\n");
System.out.println("***Date of Birth: ***");
System.out.print("Day : ");dayRead=kbInt.nextInt();
System.out.print("Month : ");monthRead=kbInt.nextInt();
System.out.print("Year : ");yearRead=kbString.nextInt();
dateOfBirth = new Date(dayRead, monthRead, yearRead);
}
catch (InputMismatchException e)
{
System.out.print("Incorrect input, please input data in the correct format!");
}
}
And finally for the person class, here is the toString
public String toString()
{
String nameAndAge = "Name = " + name + ", DOB = " + dateOfBirth;
return nameAndAge;
}
In the passenger class which inherits from Person, here is the arraylist being made and the constructor
private ArrayList<Passenger> passengers = new ArrayList<Passenger>();
//Constructor
public Passenger()
{
noOfBags = 0;
priorityBoarding = false;
id = nextid++;
}
//Initiliaze constructor
public Passenger(String titleIn, String firstNameIn, String surnameIn, int day, int month, int year, int bag, boolean pb)
{
super(titleIn, firstNameIn, surnameIn, day, month, year);
noOfBags = bag;
priorityBoarding = pb;
}
Here i add the reading of the noOfBags and priority boarding and add it to the read method in person
public void bagsPriorityRead()
{
Scanner kbInt = new Scanner(System.in);
Scanner kbString = new Scanner(System.in);
super.read();
System.out.print("Number of bags : ");bagsRead=kbString.nextInt();
System.out.print("Priority boarding (Y/N) : ");priorityRead=kbString.next().charAt(0);
}
Finally, here is the toString method in passenger
//ToString Method
public String toString()
{
return " ID: " +id + " - " + super.toString() + " \tNo of Bags: " +bagsRead + "\tDo they have priority boarding? : " +priorityRead;
}
//Added images of the adding in action and the way it is improperly formatted when printing
//Improper formatting when printing
As stated above, if anyone could point to where im going wrong/how to fix my error it would be greatly appreciated. If any more code may be needed to find the source of the problem just let me know.
Thanks in advance,
Jason
Looks like the problem, if anywhere, would be in Name::toString() or that the order of the parameters are wrong in new Name(x, y, z)
String nameAndAge = "Name = " + name + ", DOB = " + dateOfBirth;
But you haven't posted the Name class.
I am getting the error Exception in thread “main” java.lang.NullPointerException?. on my program. What I did was create an array of objects (the array is dbase[], the object is employee). the employee object creates more objects (date, name, and address) that have setter and getter methods. I am getting this error when tryinig to access these object's getter methods when trying to use something such as dbase[0].date.getMonth. I believe this is something wrong with creating the array. I have not included the date or address classes in the interest of saving space, because are basically the same as the name class. thanks for the help.
edit: The error occurred at the second line of the printing block in the main method in the for loop. It occurs at dbase[j].name.getFirst() at line 28
public class test {
public static void main (String[] args) {
int i = Input.getInt ("How many employees would you like to enter? ");
int j;
Employee [] dbase = new Employee [i];
for (j = 0; j < i; j++) {
dbase[j] = new Employee();
}
for (j = 0; j < i; j++) {
String firstName = Input.getString ("What is an employee " + (j + 1) + "'s first name?");
String lastName = Input.getString ("What is this employee's last name?");
String street = Input.getString ("On what street does this employee live?");
String city = Input.getString ("In which city does this employee live?");
String state = Input.getString ("In which state does this employee live? (abbreviation)");
String zipcode = Input.getString ("What is this employee's zip code?");
int month = Input.getInt ("In what month was this employee born? (numeric - January = 1 )");
int day = Input.getInt ("On what day was this employee born?");
int year = Input.getInt ("In what year was this employee born?");
int employeeID = Input.getInt ("What should this employee's employee id be?");
dbase[j] = new Employee(firstName, lastName, street, city, state, zipcode, month, day, year, employeeID);
}
for (j = 0; j < i; j++) {
System.out.print ( "Employee number " + (j + 1) + " is named ");
System.out.print ( dbase[j].name.getFirst() + " " + dbase[j].name.getLast() + " and lives on " + dbase[j].address.getStreet());
System.out.print ( " in " + dbase[j].address.getCity() + " " + dbase[j].address.getState() + ", " + dbase[j].address.getZipcode());
System.out.print ( ". He will be hired on " + dbase[j].date.getMonth() + "-" + dbase[j].date.getDay() + "-" + dbase[j].date.getYear() );
System.out.print ( " and his ID is " + dbase[j].getEmployeeID());
System.out.println ();
}
}
}
class Employee {
int employeeID = 0;
name name;
address address;
date date;
Employee(){
}
Employee( String firstName1, String lastName1, String street1, String city1, String state1, String zipcode1, int month1, int day1, int year1, int employeeID1 ) {
name name = new name( firstName1, lastName1 );
address address = new address( street1, city1, state1, zipcode1 );
date date = new date( month1, day1, year1);
employeeID = employeeID1;
}
int getEmployeeID() {
return employeeID;
}
}
class name {
String firstName = " ";
String lastName = " ";
name(String newFirstName, String newLastName) {
firstName = newFirstName;
lastName = newLastName;
}
String getFirst() {
return firstName;
}
String getLast() {
return lastName;
}
}
In your constructor for Employee, you're assigning to local variables, not to the fields of the same name.
Employee( String firstName1, String lastName1, String street1, String city1, String state1, String zipcode1, int month1, int day1, int year1, int employeeID1 ) {
name name = new name( firstName1, lastName1 );
address address = new address( street1, city1, state1, zipcode1 );
date date = new date( month1, day1, year1);
employeeID = employeeID1;
}
You can eliminate this problem by removing the type names from the assignment statements:
Employee( String firstName1, String lastName1, String street1, String city1, String state1, String zipcode1, int month1, int day1, int year1, int employeeID1 ) {
name = new name( firstName1, lastName1 );
address = new address( street1, city1, state1, zipcode1 );
date = new date( month1, day1, year1);
employeeID = employeeID1;
}
In addition, you should consider beginning all your type names with an uppercase character. This is almost universal Java style, and helps you identify them at a glance.
class Name { ... }
class Date { ... }
class Address { ... }
One way to reduce the likelihood of name collisions between member and local variables is to adopt a different naming scheme for the former. This is not generally accepted Java style, and some feel antipathy toward it as an incursion of a style that originated in C++. However, it can reduce risk.
class Employee {
int m_employeeID = 0;
Name m_name;
Address m_address;
Date m_date;
...
}
When you have a variable holding an object in Java, this variable is a reference to the object. That means that multiple variables can point to the same object and also that they might point to no object at all. That's null.
When you access something that belongs to an object, either a method or a field, you are dereferencing. However if the variable points to no object (that's null) you get a nullpointer exception.
In your case that could be dbase[j].name or one of the others in the last for-body. And there are two dereferenciations going on: first dbase[j] (I don't see a problem there; actually you are creating multiple objects, i.e. your first for-loop is not needed), or the value of name within your object is not set. Either because Input.getString returned null (we cannot say what that is, because that info is missing from your post) or you didn't set the value in the Employer constructor, which is the case here.
Within the constructor you create local variables.
name name = new name( firstName1, lastName1 );
Instead of
this.name = new name( firstName1, lastName1 );
As a general tip you should look into debuggers (like the one in eclipse or netbeans or whichever ide you use). They can really help you with this kind of problems.
I'm a college student doing a Java homework. I've created this program that allows user to enter a job information.
The problem is that my program doesn't return information entered.
I look at my program for a while, but I know it's something simple I'm missing.
public class Employee
{
String name; // Employee name
String employeeNumber; // Employee number
String hireDate; // Employee hire date
int shift; // Employee shift
double payRate;
public void setEmployeeNumber(String e)
{
if (isValidEmpNum(e))
{
employeeNumber = e;
}
else
{
employeeNumber = "";
}
}
public Employee(String name, String e, String hireDate, double payRate, int shift)
{
this.name = name;
this.setEmployeeNumber(e);
this.hireDate = hireDate;
this.payRate = payRate;
this.shift = shift;
}
public Employee()
{
name = "";
employeeNumber = "";
hireDate = "";
}
public void setpayRate(double payRate)
{
this.payRate = payRate;
}
public double getpayRate()
{
return payRate;
}
public void setshift(int shift)
{
this.shift = shift;
}
public int getshift()
{
return shift;
}
public void setName(String name)
{
this.name = name;
}
public void setHireDate(String hireDate)
{
this.hireDate = hireDate;
}
public String getName()
{
return name;
}
public String getEmployeeNumber()
{
return employeeNumber;
}
public String getHireDate()
{
return hireDate;
}
private boolean isValidEmpNum(String e)
{
boolean status = true;
if (e.length() != 5)
status = false;
else
{
if ((!Character.isDigit(e.charAt(0))) ||
(!Character.isDigit(e.charAt(1))) ||
(!Character.isDigit(e.charAt(2))) ||
(e.charAt(3) != '-') ||
(!Character.isLetter(e.charAt(4))) ||
(!(e.charAt(4)>= 'A' && e.charAt(4)<= 'M')))
{
status = false;
}
}
return status;
}
public String toString()
{
String str = "Name: " + name + "\nEmployee Number: ";
if (employeeNumber == "")
{
str += "INVALID EMPLOYEE NUMBER";
}
else
{
str += employeeNumber;
}
str += ("\nHire Date: " + hireDate);
return str;
}
}
I declared this in another class.
import javax.swing.JOptionPane;
public class ProductionWorkerDemo extends Employee
{
public static void main(String[] args)
{
String name; // Employee name
String employeeNumber; // Employee number
String hireDate; // Employee hire date
int shift; // Employee shift
double payRate; // Employee pay
String str;
String str2;
name = JOptionPane.showInputDialog("Enter your name: ");
employeeNumber = JOptionPane.showInputDialog("Enter your employee number: ");
hireDate = JOptionPane.showInputDialog("Enter your hire date: ");
str = JOptionPane.showInputDialog("Enter your shift: ");
payRate = Double.parseDouble(str);
str2 = JOptionPane.showInputDialog("Enter your payrate: ");
payRate = Double.parseDouble(str2);
ProductionWorkerDemo pw = new ProductionWorkerDemo();
System.out.println();
System.out.println("Name: " + pw.getName());
System.out.println("Employee Number: " + pw.getEmployeeNumber());
System.out.println("Hire Date: " + pw.getHireDate());
System.out.println("Pay Rate: " + pw.getpayRate());
System.out.println("Shift: " + pw.getshift());
}
}
You need to use an appropiate constructor or the set* methods to set the fields on the object. Currently, all of them are empty, thus the get* methods return either nothing or default values.
Also, you shouldn't extend Employee with the class containing the main method, just use the Employee class directly (the idea behind inherting from a class is to extend it, in your case you just need it as an object so save data, so don't derive from it but use it):
import javax.swing.JOptionPane;
public class ProductionWorkerDemo
{
public static void main(String[] args)
{
String name; // Employee name
String employeeNumber; // Employee number
String hireDate; // Employee hire date
int shift; // Employee shift
double payRate; // Employee pay
String str;
String str2;
name = JOptionPane.showInputDialog("Enter your name: ");
employeeNumber = JOptionPane.showInputDialog("Enter your employee number: ");
hireDate = JOptionPane.showInputDialog("Enter your hire date: ");
str = JOptionPane.showInputDialog("Enter your shift: ");
payRate = Double.parseDouble(str);
str2 = JOptionPane.showInputDialog("Enter your payrate: ");
payRate = Double.parseDouble(str2);
Employee pw = new Employee(/*provide arguments here*/);
System.out.println();
System.out.println("Name: " + pw.getName());
System.out.println("Employee Number: " + pw.getEmployeeNumber());
System.out.println("Hire Date: " + pw.getHireDate());
System.out.println("Pay Rate: " + pw.getpayRate());
System.out.println("Shift: " + pw.getshift());
}
}
You are setting the employee information on local variables only. You are not passing them to the ProductionWorkerDemo nor it's super class Employee.
You don't need to extend the Employee with the ProductionWorkerDemo as the ProductionWorkerDemo is not an Employee. You can just remove the extends Employee text.
You're not passing the variables to the Employee. You've created a constructor in the Employee class that takes them all so you can use it
Employee pw = new Employee(name, employeeNumber, hireRate, payRate, shift);
Now you'll notice that you haven't asked for the shift.
First you need to add the constructor you the Demo Class:
public class ProductionWorkerDemo extends Employee{
public ProductionWorkerDemo(String name, String e, String hireDate, double payRate, nt shift){
{
super(name, e, hireDate, payRate, shift);
}
}
Then in your class you need to instantiate:
ProductionWorkerDemo pw = new ProductionWorkerDemo(name,
employeeNumber,
hireDate,
payRate,
shift);
You are declaring variables called name, employeenumber, etc in your main method. When you try to use them, it's going to use those, not your class variables.
why don't you try making a new ProductionWorkerDemo based on the constructor you defined in Employee class?
ProductionWorkerDemo pw = new ProductionWorkerDemo(name,employeeNumber,hireDate,payRate,shift);
And also, your payRate is being assigned twice, you should change the first one to shift, and use Integer.parseInt
You have local variables in main() whose values you are setting. You then create a ProductionWorkerDemo object, who has instance variables with the same names, but are all initially empty, due to the constructor setting them that way.
You never pass your local variables in to your ProductionWorkerDemo object, so when you call the getters they return the empty values.
I fix the problem with my program, thanks for the help everyone.
I was not passing the variables to the Employee.
I add this statement to ProductionWorkerDemo class.
Employee pw = new Employee(name, employeeNumber, hireRate, payRate, shift);
P.S. You can close this thread.