Correctly calling a method in a different class | Java - java

I got a superclass Employee and subclasses of that (HourlyEmployee and CommissionEmployee) and a tester class.
When I run the program and take in user values, after it asks for hours/sales and calculates pay - the value given is 0.0. The pay is not being calculated correctly - or at all - why is this and how can I do it correctly?
abstract class Employee {
// Data members
private String firstName;
private String lastName;
private int employeeNumber;
private int numberOfEmployees;
protected int hours;
protected int sales;
protected double pay;
// Default constructor
public Employee() {
firstName = null;
lastName = null;
employeeNumber = 0;
numberOfEmployees = 0;
}
// Getter and setter methods
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getEmployeeNumber() {
return employeeNumber;
}
public void setEmployeeNumber(int employeeNumber) {
this.employeeNumber = employeeNumber;
}
public int getNumberOfEmployees() {
return numberOfEmployees;
}
public void setNumberOfEmployees(int numberOfEmployees) {
this.numberOfEmployees = numberOfEmployees;
}
// Abstract method to be implemented in sublcasses
public abstract void earnings();
#Override
public String toString(){
return "First Name: " + getFirstName() + "\n" + "Last Name: " + getLastName() + "\n" +
"Employee Number: " + getEmployeeNumber() + "\n" + "Number of Employees: "
+ getNumberOfEmployees();
}
}
`
public class HourlyEmployee extends Employee {
// Constructor
public HourlyEmployee() {
//Calls default constructor in superclass
super();
}
// Establish the amount of pay for hourly employees
int rate = 15;
// Override earnings method
#Override
public void earnings(){
pay = hours * rate;
}
// Return String representation of class
public String toString(){
return "First Name: " + getFirstName() + "Last Name: " + getLastName() +
"Employee Number: " + getEmployeeNumber() + "Number of Employees: "
+ getNumberOfEmployees();
}
}
`
public class CommissionEmployee extends Employee {
// Constructor
public CommissionEmployee() {
//Calls default constructor in superclass
super();
}
// Establish the amount of pay for hourly employees
double commission = 0.10;
// Override earnings method
#Override
public void earnings(){
pay = commission * sales;
}
// Return String representation of class
public String toString(){
return "First Name: " + getFirstName() + "Last Name: " + getLastName() +
"Employee Number: " + getEmployeeNumber() + "Number of Employees: "
+ getNumberOfEmployees();
}
}
`
import java.util.LinkedList;
import java.util.Scanner;
public class EmployeeTester {
public static void main(String[] args) {
// Protected double only visible in superclass and subclass.
// Must be declared again in tester class.
double pay;
int hours;
int sales;
// Create new LinkedList
LinkedList<Employee> employeeList = new LinkedList<>();
// Create Scanner obkect
Scanner keyboard = new Scanner(System.in);
char yes = 'y';
int x = 0;
while(yes == 'y' || yes == 'Y'){
// Declare & create a HourlyEmployee odject
HourlyEmployee employee1 = new HourlyEmployee();
employeeList.add(employee1);
System.out.print("Enter First Name: ");
String firstName = keyboard.next();
employee1.setFirstName(firstName);
employeeList.get(x).setFirstName(firstName);
System.out.print("Enter Last Name: ");
String lastName = keyboard.next();
employee1.setLastName(lastName);
employeeList.get(x).setLastName(lastName);
System.out.print("Enter Employee Number: ");
int employeeNumber = keyboard.nextInt();
employee1.setEmployeeNumber(employeeNumber);
employeeList.get(x).setEmployeeNumber(employeeNumber);
System.out.print("Enter Number of Employees: ");
int numberOfEmployees = keyboard.nextInt();
employee1.setNumberOfEmployees(numberOfEmployees);
employeeList.get(x).setNumberOfEmployees(numberOfEmployees);
System.out.print("Enter Hours Worked: ");
hours = keyboard.nextInt();
// Calculate earnings
employee1.earnings();
System.out.println(employee1.toString());
System.out.println("Total Earnings: " + employee1.pay);
x++; // increment x
System.out.print("Continue? [y/n] ");
yes = keyboard.next().charAt(0);
}
// Declare & create a CommissionEmployee odject
CommissionEmployee employee2 = new CommissionEmployee();
employeeList.add(employee2);
System.out.print("Enter First Name: ");
String firstName = keyboard.next();
employee2.setFirstName(firstName);
employeeList.get(x).setFirstName(firstName);
System.out.print("Enter Last Name: ");
String lastName = keyboard.next();
employee2.setLastName(lastName);
employeeList.get(x).setLastName(lastName);
System.out.print("Enter Employee Number: ");
int employeeNumber = keyboard.nextInt();
employee2.setEmployeeNumber(employeeNumber);
employeeList.get(x).setEmployeeNumber(employeeNumber);
System.out.print("Enter Number of Employees: ");
int numberOfEmployees = keyboard.nextInt();
employee2.setNumberOfEmployees(numberOfEmployees);
employeeList.get(x).setNumberOfEmployees(numberOfEmployees);
System.out.print("Enter Sales Made: ");
sales = keyboard.nextInt();
// Calculate earnings
employee2.earnings();
System.out.println(employee2.toString());
System.out.println("Total Earnings: " + employee2.pay);
x++; // increment x
System.out.print("Continue? [y/n] ");
yes = keyboard.next().charAt(0);
}
}

You need to set hours and sales to the employee objects, currently, they are 0, because, as int, both sales and hours get initialized to 0,
So, commission * sales will become 0 and hours * rate will become 0.
In EmployeeTester, set Hours to the HourlyEmployee object
System.out.print("Enter Hours Worked: ");
hours = keyboard.nextInt();
employee1.setHours(hours);
In EmployeeTester, set Sales to the CommissionEmployee object
System.out.print("Enter Sales Made: ");
sales = keyboard.nextInt();
employee2.setSales(sales);

You need to add setHours method in Employee
public void setHours(int hours) {
this.hours = hours;
}
call this method in EmployeeTester after getting hours from that.

Related

How to print out functions from a loop of an array of objects in java

How can I be able to print out the objects that I gave the program in case 2
What I'm trying to implement is case 2 giving me all the info about the stuff I put into case 1
At first I tried to just use the setters and getters but for some reason I was having a NullPointerException when I used the do-while method.
So I decided to use the constructor but at the same time it gave me an error when trying to implement case 2. so any help would be appreciated.
import java.util.Scanner;
public class GameProject {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int choice;
do{
GameSale[] game;
System.out.println("Hello! welcome to the menu!");
System.out.println("Please Choose your option!");
System.out.println(" 1-Enter a new game's Info \n 2-Check a game's Information \n 3- Check a game's sales \n 0-Exit");
choice = input.nextInt();
switch (choice){
case 0:
break;
case 1:
System.out.println("");
System.out.print("How many games do you want to add? : ");
int size = input.nextInt();
game = new GameSale[size];
for (int i = 0; i < size; i++) {
System.out.print("Enter Game "+(i+1) + "'s Name!: \n");
String tempname = input.next();
System.out.print("Enter the ID of the Game : \n");
int tempid = input.nextInt();
System.out.print("Enter the Game Type : \n");
String tempgametype=input.next();
System.out.print("Enter the development Company's Name : \n");
String tempgamecomp = input.next();
System.out.print("Enter the Release Sale : \n");
double temprelsale = input.nextDouble();
System.out.print("Enter the total Sales : \n");
double temptotsale = input.nextDouble();
game[i]=new GameSale(temprelsale,temptotsale,tempid,tempname,tempgamecomp,tempgametype);
}break;
case 2:
for(int i = 0; i < game.length; i++){
System.out.println(game[i].toString());
}
}while(choice!=0);
}
}
i got a class that has the setters and getters for some of the regular info
public class GameInfo {
protected int ID;
protected String GameName;
protected String DevelopmentCompany;
protected String GameType;
public GameInfo(int ID, String GameName, String DevelopmentCompany, String GameType) {
this.ID = ID;
this.GameName = GameName;
this.DevelopmentCompany = DevelopmentCompany;
this.GameType = GameType;
}
public void SetID(int id) {
this.ID = id;
}
public int GetID() {
System.out.println("The ID is " + ID);
return ID;
}
public void SetName(String Name) {
this.GameName = Name;
}
public String GetName() {
System.out.println("The Name of the Game Is " + GameName);
return GameName;
}
public void SetCompanyName(String CompanyName) {
this.DevelopmentCompany = CompanyName;
}
public String GetCompanyName() {
System.out.println("The Name Of the Development company Is " + DevelopmentCompany);
return DevelopmentCompany;
}
public void SetGameType(String GameType){
this.GameType=GameType;
}
public String GetGameType(){
System.out.println("The Game Type is : "+GameType);
return GameType;
}
}
and a super class with the sales and a constructor for the sales
public class GameSale extends GameInfo {
protected double ReleaseSales;
protected double TotalSales;
public GameSale(double ReleaseSales, double TotalSales, int ID, String GameName, String DevelopmentCompany, String GameType) {
super(ID, GameName, DevelopmentCompany, GameType);
this.ReleaseSales = ReleaseSales;
this.TotalSales = TotalSales;
}
public void SetReleaseSales(double RelSale){
this.ReleaseSales=RelSale;
}
public void SetTotalSales(double totSales){
this.TotalSales=totSales;
}
public double GetReleaseSales(){
System.out.println("The Release Sales Are "+ReleaseSales );
return ReleaseSales;
}
public double GetTotalSales(){
System.out.println("The Total Sales Are "+TotalSales);
return TotalSales;
}
}
Answered by Alex (thanks a lot dude)
here's a temporary fix just for debugging so far by initializing the array dimensions outside the do-while loop
main
import java.util.Scanner;
public class GameProject {
public static void main(String[] args) {
Scanner input = new Scanner(System. in );
int choice;
GameSale[] games = new GameSale[1];
do {
System.out.println("Hello! welcome to the menu!");
System.out.println("Please Choose your option!");
System.out.println(" 1-Enter a new game's Info \n 2-Check a game's Information \n 3- Check a game's sales \n 0-Exit");
choice = input.nextInt();
switch (choice) {
case 0:
break;
case 1:
for (int i = 0; i < games.length; i++) {
System.out.print("Enter Game " + (i + 1) + "'s Name!: \n");
String tempname = input.next();
System.out.print("Enter the ID of the Game : \n");
int tempid = input.nextInt();
System.out.print("Enter the Game Type : \n");
String tempgametype = input.next();
System.out.print("Enter the development Company's Name : \n");
String tempgamecomp = input.next();
System.out.print("Enter the Release Sale : \n");
double temprelsale = input.nextDouble();
System.out.print("Enter the total Sales : \n");
double temptotsale = input.nextDouble();
games[i] = new GameSale(temprelsale, temptotsale, tempid, tempname, tempgamecomp, tempgametype);
}
break;
case 2:
for (int i = 0; i < games.length; i++) {
System.out.println(games[i].toString());
}
}
} while ( choice != 0 );
}
}
game info
public class GameInfo {
protected int ID;
protected String GameName;
protected String DevelopmentCompany;
protected String GameType;
public GameInfo(int ID, String GameName, String DevelopmentCompany, String GameType) {
this.ID = ID;
this.GameName = GameName;
this.DevelopmentCompany = DevelopmentCompany;
this.GameType = GameType;
}
public void SetID(int id) {
this.ID = id;
}
public int GetID() {
System.out.println("The ID is " + ID);
return ID;
}
public void SetName(String Name) {
this.GameName = Name;
}
public String GetName() {
System.out.println("The Name of the Game Is " + GameName);
return GameName;
}
public void SetCompanyName(String CompanyName) {
this.DevelopmentCompany = CompanyName;
}
public String GetCompanyName() {
System.out.println("The Name Of the Development company Is " + DevelopmentCompany);
return DevelopmentCompany;
}
public void SetGameType(String GameType){
this.GameType=GameType;
}
public String GetGameType(){
System.out.println("The Game Type is : "+GameType);
return GameType;
}
}
game sale
public class GameSale extends GameInfo {
protected double ReleaseSales;
protected double TotalSales;
public GameSale(double ReleaseSales, double TotalSales, int ID, String GameName, String DevelopmentCompany, String GameType) {
super(ID, GameName, DevelopmentCompany, GameType);
this.ReleaseSales = ReleaseSales;
this.TotalSales = TotalSales;
}
public void SetReleaseSales(double RelSale){
this.ReleaseSales=RelSale;
}
public void SetTotalSales(double totSales){
this.TotalSales=totSales;
}
public double GetReleaseSales(){
System.out.println("The Release Sales Are "+ReleaseSales );
return ReleaseSales;
}
public double GetTotalSales(){
System.out.println("The Total Sales Are "+TotalSales);
return TotalSales;
}
public String toString(){
return this.ID + " " + this.GameName + " " + this.DevelopmentCompany + " " + this.GameType;
}}
Solution
toString()
In your class you should implement a toString() method.
This basically returns all the property values of your object as a String
public String toString(){
return this.ID + " " + this.GameName + " " + this.DevelopmentCompany + " " + this.GameType;
}
Then call it on your object in case2
game[i].toString()
Display
To list all games you have to iterate over your gamesArray and print out the informations with your toString() method;
for(int i = 0; i < games.length(); i++){
System.out.println(game[i].toString());
}
Scope
Create the games array outside of you case1 scope.
GameSale[] game = new GameSale[SomeFixedSize];
If you wanted to print a game's info at a given index in case 2:
if (game == null) { // Break if no game exists
System.out.println("There is no games to show!");
break;
}
System.out.print("Enter game index to show information: ");
int index = input.nextInt();
// Break if index is not in bounds
if (index < 0 || index > game.length) {
System.out.println("Incorrect index");
break;
}
System.out.println("Info of game: " + game[index].toString());
This code should ask for index as input and prints the info of the game and it will print 'There is no games to show!' if there was no any game added yet
Note you must add the toString() method in your GameSale class:
#Override
public String toString() {
return "ID: " + this.ID + " Name: " + this.GameName + " Development Company: " +
this.DevelopmentCompany + " Game Type: " + this.GameType + " Release Sales: " + ReleaseSales + " Total Sales: " + TotalSales;
}
also move the decleration of the game variable out of the scope of the do-while loop (above it) it will look like
GameSale[] game = null;
do { ...
Also if you want case 2 to show all games info you can replace the index part with a loop that iterates the whole 'game' array and prints every element's toString.

Constructor error with encapsulation

I have my code in 3 different files using encapsulation (Data hiding) and i have 1 problem at the very end of my code in my if and else statement (very bottom) when trying to call the classes from the other 2 documents. I will put the code in 1st document to 3rd document. Any suggestions on what I did wrong?
// FIRST DOCUMENT
public class CollegeCourse { //class name
//variables
String deptName;
int courseNum;
int credits = 3;
double fee;
//constructor
public CollegeCourse(String department, int course, int Credits) {
deptName = department;
courseNum = course;
credits = Credits;
fee = credits * 120;
}
//getters setters
public String getdepartment() {
return deptName;
}
public String setdepartment(String dept) {
return dept = deptName;
}
public int getcourse() {
return courseNum;
}
public int setcourse(int c) {
return c = courseNum;
}
public int getCredits() {
return credits;
}
public int setCredits(int cred) {
return cred = credits;
}
public void display()
{
System.out.println("Department: " + deptName);
System.out.println("Course Number: " + courseNum);
System.out.println("Credits: " + credits);
System.out.println("Fee: $" + fee);
}
}
//SECOND DOCUMENT
public class LabCourse extends CollegeCourse { //polymorphism extending CollegeCourse class into LabCourse class.
//constructor
public LabCourse(String department, int course, int Credits){
//add 50 dollars to the fee
super(department, course, Credits);
fee = fee + 50;
}
//display the course
public void display(){
System.out.print("This course is a lab course" + fee);
System.out.println("Department: " + deptName);
System.out.println("Course Number: " + courseNum);
System.out.println("Credits: " + credits);
System.out.println("Fee: $" + fee);
}
}
//THIRD DOCUMENT MAIN HEADER
import java.util.Scanner;
public class UseCourse {
public static void main(String[] args){
String s, c, cd;
Scanner input = new Scanner(System.in);
System.out.print("Enter: BIO, CHEM, ENG, MATH: ");
s = input.nextLine();
System.out.print("What is the course number: ");
c = input.nextLine();
System.out.print("How many credits: ");
cd = input.nextLine();
if(s.equals ("BIO") || s.equals ("CHEM")){
LabCourse lc = new LabCourse(department, course, Credits); //here is my problem, it can't find the CollegeCourse class department, course,//and credits...
lc.display();
}
else {
CollegeCourse cc = new CollegeCourse(department, course, Credits); //here is my problem, it can't find the CollegeCourse class department, course,//and credits...
cc.display();
}
}
}
Here is the error that i'm getting.
UseCourse.java:24: error: cannot find symbol
LabCourse lc = new LabCourse(department, course, Credits);
^
And it repeats for each error "department, course, Credits"
UseCourse.java:29: error: cannot find symbol
CollegeCourse cc = new CollegeCourse(department, course, Credits);
^
Your parameters in your constructor call are all wrong. Neither department, course or Credits are defined, so you would need to use s, c and cd instead, as those are the variables you're using for your input.
Furthermore, you need to read c and cd as integers and pass those to your constructor as follows:
System.out.print("What is the course number: ");
int c = input.nextInt();
System.out.print("How many credits: ");
int cd = input.nextInt();
// ...
LabCourse lc = new LabCourse(s, c, cd);

Inheritance code returns no value

I created a super class called Employee, with a subclass called ProductionWorker and a driver called ProductionWorkerDriver. The program takes my entered info and returns the String values from the Employee class, but not the double and int values from the ProductionWorker class. The program I'm using said I had to initialize the values of those as 0, and I'm thinking that's why they show up as zero when compiled. However, the program won't compile without that, so I'm not sure what to do.
public class Employee {
private String name;
private String employeeNumber;
private String hireDate;
public Employee(String n, String num, String date) {
name = n;
employeeNumber = num;
hireDate = date;
}
public Employee() {
name = "";
employeeNumber = "";
hireDate = "";
}
public void setName(String n) {
name = n;
}
public void setEmployeeNumber(String e) {
employeeNumber = e;
}
public void setHireDate(String h) {
hireDate = h;
}
public String getName() {
return name;
}
public String getEmployeeNumber() {
return employeeNumber;
}
public String getHireDate() {
return hireDate;
}
public String toString() {
String str = "Employee Name: " + name
+ "\nEmployee #: " + employeeNumber
+ "\nHire Date: " + hireDate;
return str;
}
} //end of Employee class
//beginning of ProductionWorker class
import java.text.DecimalFormat;
public class ProductionWorker extends Employee {
private int shift;
private double payRate;
public int DAY_SHIFT = 1;
public int NIGHT_SHIFT = 2;
public ProductionWorker(String n, String num, String date, int sh, double rate) {
super(n, num, date);
shift = sh;
payRate = rate;
}
public ProductionWorker() {
}
public void setShift(int s) {
shift = s;
}
public void setPayRate(double p) {
payRate = p;
}
public int getShift() {
return shift;
}
public double getPayRate() {
return payRate;
}
public String toString() {
DecimalFormat dollar = new DecimalFormat("#,##0.00");
String str = super.toString() + "\nShift: " + shift
+ "\nPay Rate: $" + dollar.format(payRate);
return str;
}
}//end of ProductionWorker class
//beginning of ProductionWorkerDriver
import java.util.Scanner;
public class ProductionWorkerDriver {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String name = null;
String employeeNumber = null;
String hireDate = null;
int shift = 0;
double payRate = 0;
int DAY_SHIFT = 1;
int NIGHT_SHIFT = 2;
Employee info = new Employee(name, employeeNumber, hireDate);
System.out.println("Employee Name:");
name = keyboard.nextLine();
System.out.println("Employee #:");
employeeNumber = keyboard.nextLine();
System.out.println("Hire Date:");
hireDate = keyboard.nextLine();
ProductionWorker info2 = new ProductionWorker(name, employeeNumber, hireDate, shift, payRate);
System.out.println("Shift 1 or 2:");
shift = keyboard.nextInt();
System.out.println("Pay Rate:");
payRate = keyboard.nextDouble();
System.out.println(info2.toString());
}
}//end of ProductionWorkerDriver
You're not doing anything with the data you've entered:
System.out.println("Shift 1 or 2:");
shift = keyboard.nextInt();
System.out.println("Pay Rate:");
payRate = keyboard.nextDouble();
... the shift and payRate variables aren't used again. Changing the values of these local variables doesn't change the values in the instance that you created earlier using the same variables.
You should either be calling:
info2.setShift(shift);
info2.setPayRate(payRate);
... or better, wait until after you've asked those questions before you construct the instance. You're also not using your info variable at all. Your entire main method can be improved to:
Scanner keyboard = new Scanner(System.in);
System.out.println("Employee Name:");
String name = keyboard.nextLine();
System.out.println("Employee #:");
String employeeNumber = keyboard.nextLine();
System.out.println("Hire Date:");
String hireDate = keyboard.nextLine();
System.out.println("Shift 1 or 2:");
int shift = keyboard.nextInt();
System.out.println("Pay Rate:");
double payRate = keyboard.nextDouble();
ProductionWorker worker =
new ProductionWorker(name, employeeNumber, hireDate, shift, payRate);
System.out.println(worker);
Notice how in each case we don't declare a variable until we need it.
Note that the fact that your employee number and your hire date are both String values is a bit of a worry, and it's a bad idea to use double for currency values - get into the habit of using BigDecimal, or use an integer to represent a number of cents/pennies/whatever.
This:
System.out.println("Shift 1 or 2:");
shift = keyboard.nextInt();
System.out.println("Pay Rate:");
payRate = keyboard.nextDouble();
Will update the shift and payRate of your main method:
public static void main(String[] args)
{
//...
int shift = 0;
double payRate = 0;
Because you're outputting the values from the ProductionWorker, and those values are never updated, it will always output 0. Simply because you initialize ProductionWorker with those variables does not mean that the reference shift in the main method will point to the same place in memory as the reference shift inside ProductionWorker.

ArrayList Object

I am using the ArrayList Object to create an employee object of type employee...I implement the class and it seems to work, but my problem is that when I insert the employees into the ArrayList it is automatically doesn't insert it. Why is that?
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author
*/
import java.util.*;
class Employee {
private String fname;
private String lname;
public Employee (String fname, String lname){
this.fname = fname;
this.lname = lname;
}
public Employee (){
}
public String getLastName(){
return this.lname;
}
public void setLastName(String lname){
this.lname = lname;
}
public String getFirstName(){
return this.fname;
}
public void setFirstName (String fname){
this.fname = fname;
}
public String toString(){
return this.getClass().getName() +" [ "
+ this.fname + " "
+ this.lname + " ]\n ";
}
public Object clone(){ //Object is used as a template
Employee emp;
emp = new Employee(this.fname, this.lname);
return emp;
}
}
//start of main
public class main
{
static Scanner input = new Scanner(System.in);
public static final int MAX_EMPLOYEES = 10;
public static void main(String[] args) {
String fname, lname;
int num;
System.out.print("Enter the number of employees in your system: ");
num = input.nextInt();
ArrayList<Employee> emp = new ArrayList<Employee>(num);
System.out.print("Enter the first name: ");
fname = input.next();
System.out.println();
System.out.print("Enter the last name: ");
lname = input.next();
System.out.println();
for (int x = 1; x < num; x++)
{
System.out.print("Enter the first name: ");
fname = input.next();
System.out.println();
System.out.print("Enter the last name: ");
lname = input.next();
System.out.println();
emp.add(new Employee(fname,lname));
}
num = emp.size();
System.out.println(num);
System.out.println(emp);
}
}
Add:
emp.add(new Employee(fname,lname));
just before your for loop or rewrite your for loop conditional as:
for (int x = 0; x < num; x++)
and get rid of the
System.out.print("Enter the first name: ");
fname = input.next();
System.out.println();
System.out.print("Enter the last name: ");
lname = input.next();
System.out.println();
before the for loop.
Your loop is running 1 less time than is required.
for(int i=0;i<num; i++){
This should fix it.

I need help, my java program is returning nothing when i compile it

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.

Categories