I am extremely new to java and am very close to finishing a project I have been trying to finish for a long time. Whenever I try to run the code. It gives a null pointer exception as soon as the constructer is called. My code is listed below and any help would be appreciated.
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 register.");
int arraySize = Input.nextInt();
Input.nextLine();
Employee employee = new Employee(arraySize);
String namesTemp;
String streetTemp;
String cityTemp;
String stateTemp;
String zipCodeTemp;
String dateOfHireTemp;
for(int x = 0; x < arraySize; 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();
System.out.println("Please enter the date of hire for Employee " + (x + 1));
dateOfHireTemp = Input.nextLine();
employee.addEmployee(x, namesTemp, streetTemp, cityTemp, stateTemp, zipCodeTemp, dateOfHireTemp);
System.out.println("The employee ID for employee " + (x + 1) + " is " + (x + 1));
}
for(int x = 0; x < arraySize; x++)
{
String info[] = employee.getEmployeeInfo(x);
System.out.println("Employee ID: " + (x + 1));
System.out.println("Name: " + info[0]);
System.out.println("Address: " + info[1]);
System.out.println("Date of Hire: " + info[2]);
}
}
}
Employee class:
public class Employee
{
private EmployeeName name;
private EmployeeAddress address;
private EmployeeDateOfHire hireDate;
public Employee(int arraySize)
{
}
public void addEmployee(int x, String name, String street, String city, String state, String zipCode, String hireDate)
{
this.name.setName(x, name);
this.address.setAddress(x, street, city, state, zipCode);
this.hireDate.addDateOfHire(x, hireDate);
}
public String[] getEmployeeInfo(int x)
{
String info[] = new String[3];
info[0] = name.getName(x);
info[1] = address.getAddress(x);
info[2] = hireDate.getDateOfHire(x);
return info;
}
}
EDIT--
Here is how I wrote my data classes. They are all written in the same format.
Name Class:
public class EmployeeName
{
private String names[];
public void setArray(int x)
{
String array[] = new String[x];
this.names = array;
}
public void setName(int x, String name)
{
this.names[x] = name;
}
public String getName(int x)
{
return this.names[x];
}
}
In the addEmployee() method
public void addEmployee(int x, String name, String street, String city, String state, String zipCode, String hireDate)
this.name.setName(x, name);
this.address.setAddress(x, street, city, state, zipCode);
this.hireDate.addDateOfHire(x, hireDate);
}
you haven't initialized name or the other fields. By default, instance fields will be initialized to null. Trying to dereference null will cause a NullPointerException.
You should initialize those fields, for example in your Constructor
public Employee(int arraySize)
{
this.name = new EmployeeName();
this.address = new EmployeeAddress();
this.hireDate = new EmployeeDateOfHire();
}
I don't know what those classes look like.
Seeing
private String names[];
public void setArray(int x)
{
String array[] = new String[x];
this.names = array;
}
public void setName(int x, String name)
{
this.names[x] = name;
}
You call setName() which would also throw a NullPointerException because you're trying to dereference names but it's null. You would have to call setArray() first but then that would fail too because if x is 0, you will create an array of size 0 but then try to access the element at index 0, which would not exist. If x was 1, you would create array of size 1 but try to access the element at index 1 (second element), which would throw an IndexOutOfBoundsException.
Seriously rethink your design. Why is this EmployeeName class so complicated? Why don't you just have a String field name. Or two fields, firstName and lastName?
Related
I am trying to utilize the toString() in a class I have called Employee(). I have a 1D array of type Employee, which stores Employee Data, which include the Employee ID, Employee Name, Employee Address, and Employee Hire Date. I want the user to specify the amount of employees, and then enter the relevant data for however many employees the user wants. I then want to print the result for the user with the information entered. I keep getting some results that are null. I tried using an If statement that printed output if it didn't equal null, but that didn't work. I know the output works if I print out a single variable, such as address, but I want all variables to print out. Thank you for any help.
public class Address
{
public String address;
public void getAddress(String a)
{
address = a;
}
public String toString()
{
return address;
}
}
public class Name
{
String name;
public void getName(String n)
{
name = n;
}
public String toString()
{
return name;
}
}
public class Date
{
public String date;
public String date1;
public void getDate(int d, int m, int y)
{
date1 = (m + "/" + d + "/" + y);
}
public String toString()
{
return date1;
}
}
import java.util.Scanner;
public class Employee
{
private int number;
private Name name1 = new Name();
private Address address1 = new Address();
private Date hireDate = new Date();
String number1;
public void getDate1(int d, int m, int y)
{
hireDate.getDate(d, m, y);
}
public void getID(int x)
{
number = x;
}
public void setName( String n)
{
name1.getName(n);
}
public void getAddress(String a)
{
address1.address = a;
}
String z;
public String toString()
{
number1 = String.valueOf(number);
String name2 = String.valueOf(name1);
String address2 = String.valueOf(address1);
String hireDate2 = String.valueOf(hireDate);
z = number1 + " " + name2 + " " + address2 + " " + hireDate2;
return z;
}
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter amount of Employees: ");
int input1 = input.nextInt();
input.nextLine();
for (int i = 0; i < input1; i++)
{
Employee [] employees = new Employee[4];
System.out.println("Please enter the employee ID: ");
int employeeID = input.nextInt();
input.nextLine();
employees[0] = new Employee();
employees[0].getID(employeeID);
System.out.println("Please enter the employees Name: ");
String name2 = input.nextLine();
employees[1] = new Employee();
employees[1].setName(name2);
System.out.println("Please enter the employee's address: ");
String address2 = input.nextLine();
employees[2] = new Employee();
employees[2].getAddress(address2);
System.out.println("please enter hire date, day (1-31),");
System.out.print("month (1-12), year (1901 - 2019) in order on seperate");
System.out.print(" lines: ");
int input2 = input.nextInt();
int input3 = input.nextInt();
int input4 = input.nextInt();
employees[3] = new Employee();
employees[3].getDate1(input2, input3, input4);
for (int p = 0; p < employees.length; p++)
{
System.out.println(employees[p]);
}
}
}
}
I have create classes which were needed. You can change them but you are creating employee object every time. I have corrected the code debug it and you will know what was wrong.
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
class Name {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class Address {
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
public class Employee {
private int number;
private Name name1 = new Name();
private Address address1 = new Address();
private Date hireDate = new Date();
String number1;
public void getDate1(int d, int m, int y) {
Calendar calendar = Calendar.getInstance();
calendar.set(y, m, d);
hireDate = calendar.getTime();
}
public void getID(int x) {
number = x;
}
public void setName(String n) {
name1.setName(n);
}
public void getAddress(String a) {
address1.setAddress(a);
}
String z;
public String toString() {
number1 = String.valueOf(number);
String name2 = name1.getName();
String address2 = address1.getAddress();
String hireDate2 = String.valueOf(hireDate);
z = number1 + " " + name2 + " " + address2 + " " + hireDate2;
return z;
}
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter amount of Employees: ");
int input1 = input.nextInt();
input.nextLine();
Employee[] employees = new Employee[input1];
for (int i = 0; i < input1; i++) {
System.out.println("Please enter the employee ID: ");
int employeeID = input.nextInt();
input.nextLine();
employees[i] = new Employee();
employees[i].getID(employeeID);
System.out.println("Please enter the employees Name: ");
String name2 = input.nextLine();
employees[i].setName(name2);
System.out.println("Please enter the employee's address: ");
String address2 = input.nextLine();
employees[i].getAddress(address2);
System.out.println("please enter hire date, day (1-31),");
System.out.print("month (1-12), year (1901 - 2019) in order on seperate");
System.out.print(" lines: ");
int input2 = input.nextInt();
int input3 = input.nextInt();
int input4 = input.nextInt();
employees[i].getDate1(input2, input3, input4);
System.out.println(employees[i]);
}
}
}
I have another small class containing the main method that display the
invoice, but the toString method here is only displaying the last item
entered, not the three itemnames,quantities, prices and totalPrice.
I have doubts about addItemLine and toString.
Can someone see what I am missing here?
I was enable to past the lineItem class code.
import java.util.ArrayList;
import java.util.Scanner;
public class Transaction {
private ArrayList<lineItem> lineItems;
private int customerID;
private String customerName;
public Transaction (int customerID, String customerName){
this.customerID= customerID;
this.customerName= customerName;
this.lineItems= new ArrayList<>();
}
public int getcustomerID(){
return customerID;
}
public void setcustomerID(int customerID){
this.customerID = customerID;
}
public String getcustomerName(){
return customerName;
}
public void setcustomerName(String customerName){
this.customerName = customerName;
}
public ArrayList addItemLine(lineItem line){
Scanner mykey=new Scanner(System.in);
for (int i=0; i<2;i++){
String k= line.getItemName();
int m= line.getQuantity();
double d= line.getPrice();
System.out.println("enter item name:");
k = mykey.next();
line.setItemName(k);
System.out.println("enter quantity:");
m= mykey.nextInt();
line.setQuantity(m);
System.out.println("enter unit price:");
d= mykey.nextDouble();
line.setPrice(d);
line.getItemName(); line.getQuantity(); line.getPrice();
lineItems.add(new lineItem(k,m,d));
}
return this.lineItems;
}
public void updateItem(String item, int quant, double pri){
lineItem l= new lineItem(item, quant, pri);
int m=0;
m= l.getQuantity();
m=m+quant;
double tot=0;
}
public double getTotalPrice(){
double totalPrice = 0;
for (int i =0;i<2; i++){
lineItem item = lineItems.get(i);
totalPrice = totalPrice + item.getTotalPrice();
}
return totalPrice;
}
public String getLineItem( String s, int d, double k){
lineItem o= new lineItem(s,d,k);
for (int i =0;i<2; i++){
if (!s.equals(o.getItemName()))
System.out.println("item not found");
else
s= (o.getItemName() + o.getQuantity() + o.getPrice());
}
return s;
}
public String toString(lineItem lin) {
String a="", b="";
a=("Customer ID:" + this.getcustomerID() + "\n" + "Customer Name: " +
this.getcustomerName());
for (int i=0; i<2;i++){
b= ("\n\n" + lin.getItemName() + "\t" + "Qty" + lin.getQuantity() + "
"
+ "#" + lin.getPrice() + " "+ "\t" + "$" + lin.getTotalPrice());
}
return a + b;
}
TransactionTesting:
import java.util.Scanner;
public class TransactionTesting {
public static void main(String args[]) {
String m=""; int g=0; double r=0; int id=0; String name="";
Scanner mykey= new Scanner(System.in);
System.out.println("enter customer name:");
name= mykey.nextLine();
System.out.println("enter customer ID:");
id=mykey.nextInt();
Transaction mytrans= new Transaction(id, name);
lineItem line= new lineItem(m,g,r);
mytrans.addItemLine(line);
System.out.println(mytrans.toString(line));
}
}
Change your toString() method like this:
public String toString() {
String a="", b="";
a=("Customer ID:" + this.getcustomerID() + "\n" + "Customer Name: " +
this.getcustomerName());
for (lineItem item : this.lineItems)
b += ("\n\n" + item.getItemName() + "\t" + "Qty" + item.getQuantity() + " "
+ "#" + item.getPrice() + " "+ "\t" + "$" + item.getPrice());
return a + b;
}
and from your test class call this method as the following:
System.out.println(mytrans.toString());
You don't need any argument in order to print your entire list.
Try to refactor your code a bit. It works, but it can be written better and better ;)
1) The call
System.out.println(mytrans.toString(line));
is printing out the single lineitem that is passed to it. What you probably intended was for Transaction.toString() to iterate over its list Transaction.lineItems and print each item in turn.
In fact Transaction.toString() doesn't need to take in a lineItem argument, the method should merely print out the internals of the class instance.
2) There is a similar confusion in Transacton.addItemLine(). It accepts a lineItem, prompts the user for new values, updates lineItem.. then constructs a new lineItem to store in Transaction.lineItems. It isn't actually causing a bug that I can see but you should get rid of the lineItem argument entirely; addItemLine doesn't need it.
3) Incidentally:
for (int i=0; i<2;i++){ }
loops twice, not three times. I trust you would have caught that in testing.
4) There is also a line of code near the end of addItemLine that doesn't actually do anything! Maybe you can spot that one on your own.
There are some other issues but those are the ones that leapt out at me.
Just a quick non-tested solution that may work. Something is copied from your code, something is changed because your code was wrong.
// If you create this inside the method than you'll lose everything everytime you call addItemLine
private ArrayList<lineItem> lineItems;
public void addItemLine(lineItem line){
Scanner mykey=new Scanner(System.in);
for (int i=0; i<2;i++){
String k= line.getItemName();
int m= line.getQuantity();
double d= line.getPrice();
System.out.println("enter item name:");
k = mykey.next();
line.setItemName(k);
System.out.println("enter quantity:");
m= mykey.nextInt();
line.setQuantity(m);
System.out.println("enter unit price:");
d= mykey.nextDouble();
line.setPrice(d);
line.getItemName(); line.getQuantity(); line.getPrice();
lineItems.add(new lineItem(k,m,d));
// This doesn't have to return anything, it just adds to the list
}
// No parameteres, this should build the string for the current object
public String toString() {
// String concatenation is not the best idea, StringBuilder is better
StringBuilder sb = new StringBuilder();
// If you want to print all of them then you need to iterate over the list
for (lineItem item : lineItems){
sb.append("Customer ID:" + this.getcustomerID() + "\n" + "Customer Name: " + this.getcustomerName());
for (int i=0; i<2;i++){
// Copied from your code
sb.append("\n\n" + lin.getItemName() + "\t" + "Qty" + lin.getQuantity() + " "+ "#" + lin.getPrice() + " "+ "\t" + "$" + lin.getTotalPrice());
}
sb.append("\n);
}
return sb.toString();
}
It seems that you don't understand how to create a Java object, or how to keep your application model separate from your application view.
Here's a test run of your code, after I made some changes.
Enter customer name: Gilbert
Enter customer ID: 123
Enter item name: Spinach
Enter quantity: 5
Enter unit price: .89
Customer ID: 123
Customer Name: Gilbert
Spinach Qty 5 #0.89 $4.45
Enter item name: Corn
Enter quantity: 12
Enter unit price: .29
Customer ID: 123
Customer Name: Gilbert
Corn Qty 12 #0.29 $3.4799999999999995
Enter item name:
First, let's look at your Java objects. The first Java object which you didn't include, is LineItem. Note that Java class names start with a capital letter.
package com.ggl.transaction;
public class LineItem {
private String itemName;
private int quantity;
private double price;
public LineItem(String itemName, int quantity, double price) {
this.itemName = itemName;
this.quantity = quantity;
this.price = price;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public double getTotalPrice() {
return price * quantity;
}
}
A Java object consists of class fields, and getters and setters for the fields.
Next, here's your Transaction class.
package com.ggl.transaction;
import java.util.ArrayList;
import java.util.List;
public class Transaction {
private List<LineItem> lineItems;
private int customerID;
private String customerName;
public Transaction(int customerID, String customerName) {
this.customerID = customerID;
this.customerName = customerName;
this.lineItems = new ArrayList<>();
}
public int getcustomerID() {
return customerID;
}
public void setcustomerID(int customerID) {
this.customerID = customerID;
}
public String getcustomerName() {
return customerName;
}
public void setcustomerName(String customerName) {
this.customerName = customerName;
}
public void addItemLine(LineItem line) {
this.lineItems.add(line);
}
public void updateItem(String item, int quant, double pri) {
LineItem l = new LineItem(item, quant, pri);
int m = 0;
m = l.getQuantity();
m = m + quant;
l.setQuantity(m);
}
public double getTotalPrice() {
double totalPrice = 0;
for (int i = 0; i < 2; i++) {
LineItem item = lineItems.get(i);
totalPrice = totalPrice + item.getTotalPrice();
}
return totalPrice;
}
public String getLineItem(String s, int d, double k) {
LineItem o = new LineItem(s, d, k);
for (int i = 0; i < 2; i++) {
if (!s.equals(o.getItemName()))
System.out.println("item not found");
else
s = (o.getItemName() + o.getQuantity() + o.getPrice());
}
return s;
}
public String toItemString(LineItem lin) {
String b = "";
String a = ("Customer ID: " + this.getcustomerID() + "\n"
+ "Customer Name: " + this.getcustomerName());
for (int i = 0; i < 2; i++) {
b = ("\n\n" + lin.getItemName() + "\t" + "Qty " + lin.getQuantity()
+ " " + "#" + lin.getPrice() + " " + "\t" + "$"
+ lin.getTotalPrice() + "\n");
}
return a + b;
}
}
I simplified your addItemLine class. Code that receives input using the Scanner class belongs in your TransactionTesting class.
I renamed your toString method to toItemString. toString is a method of the Object class. Since your method has a parameter, I renamed it to lessen any confusion.
Finally, here's your TransactionTesting class. I fixed it up so it would work. You can specify any number of line items. To stop processing, just enter a blank item name.
package com.ggl.transaction;
import java.util.Scanner;
public class TransactionTesting {
public static void main(String args[]) {
Scanner mykey = new Scanner(System.in);
System.out.print("Enter customer name: ");
String name = mykey.nextLine().trim();
System.out.print("Enter customer ID: ");
int id = Integer.valueOf(mykey.nextLine().trim());
Transaction mytrans = new Transaction(id, name);
boolean processing = true;
while (processing) {
System.out.print("Enter item name: ");
String k = mykey.nextLine().trim();
if (k.equals("")) {
processing = false;
} else {
System.out.print("Enter quantity: ");
int m = Integer.valueOf(mykey.nextLine().trim());
System.out.print("Enter unit price: ");
double d = Double.valueOf(mykey.nextLine().trim());
LineItem lineItem = new LineItem(k, m, d);
mytrans.addItemLine(lineItem);
System.out.println("\n" + mytrans.toItemString(lineItem));
}
}
mykey.close();
}
}
Remember, keep your application model (LineItem & Transaction) separate from your application view (TransactionTesting).
Simply put, in your method "addItemLine" you take data from 1 lineItem, overwrite it with some keyboard input, and the put in the list 2 other lineItem instances.
Then in the test code you print the original lineItem, which is not even in the list.
The method itself iterates on nothing, just creates twice the same string "b".
I suggest you to look at some tutorials on arrays and for loops.
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 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.
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.