I am currently working on a school project where we are learning to use Arrays of Objects. I have come across two separate issues along the way which I would like to address. I am using the NetBeans IDE with all code I mention below.
Firstly, after I have added values to the array, I attempt to use a list button which should display the values in a jtextArea. There are no noticeable errors that pop-up although, all the values say "null" instead of the user inputted values they should say. Since there are 5 values the program displays "null null null null null". I am not sure as to why this is and any input would be appreciated.
Secondly, I am attempting to allow the user to remove information based on one of the 5 values which have been stored. In the case of this program the user must enter the "Employee ID" to remove all of said employee's data from the program list. I am having trouble doing this as you will be able to see in my code below.
So to sum things up:
How can I correct this random "null" error so that the imputed data is displayed?
How can I effectively remove the values of a given index based on user input for the idNumber?
Things to keep in mind:
- I need to use an array of objects
- I am fairly new to coding so please excuse my possible ignorance
- Anything that appears to be missing is likely included in the NetBeans code and therefore may not have been included, this is the main code of concern in my mind
Here's the code:
//ArrayList of Objects Declared
ArrayList <employees> list = new ArrayList <employees>();
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {
employees e;
//Declaring Strings
String idNumber, firstName, lastName, annualSalary, startDate;
//Reads the input fields
idNumber = idInput.getText();
firstName = fNameInput.getText();
lastName = lNameInput.getText();
annualSalary = annualInput.getText();
startDate = startDateInput.getText();
//Sends input information as a class
e = new employees(idNumber, firstName, lastName, annualSalary, startDate);
//If data is missing, the user will receive and error message
if (idNumber.isEmpty()||firstName.isEmpty()||lastName.isEmpty()||annualSalary.isEmpty()||startDate.isEmpty()){
infoOutput.setText("Please fill out all catagories!");
}
//Otherwise, the information provided will be stored
else {
list.add(e);
infoOutput.setText("");
infoOutput.setText("Employee data added!");
}
}
private void removeButtonActionPerformed(java.awt.event.ActionEvent evt) {
//Reset infoOutput
infoOutput.setText("");
employees e;
//Declaring Strings
String idNumber, firstName, lastName, annualSalary, startDate;
//Reads the input fields
idNumber = idInput.getText();
firstName = fNameInput.getText();
lastName = lNameInput.getText();
annualSalary = annualInput.getText();
startDate = startDateInput.getText();
//Sends input information as a class
e = new employees(idNumber, firstName, lastName, annualSalary, startDate);
//Determines if the requested employee exists in the list
for (int index = 0; index < list.size(); index++) {
//If the employee ID is found, their information is removed
if (list.get(index).toString() == idNumber){
infoOutput.setText("Employee data removed!");
list.remove(index);
}
//Otherwise, an error message is displayed to the user
else{
infoOutput.setText("The employee ID " + idNumber + " was not found!");
}
}
}
class employees {
String idNumber, firstName, lastName, annualSalary, startDate;
employees(String idNumber, String firstName, String lastName, String annualSalary, String startDate) {
idNumber = idInput.getText();
firstName = fNameInput.getText();
lastName = lNameInput.getText();
annualSalary = annualInput.getText();
startDate = startDateInput.getText();
}
}
private void listButtonActionPerformed(java.awt.event.ActionEvent evt) {
//Reset temp
String temp = "";
//List all of the stored data
for (int x = 0; x <= list.size()-1; x++) {
temp = temp + list.get(x).idNumber + " "
+ list.get(x).firstName + " "
+ list.get(x).lastName + " "
+ list.get(x).annualSalary + " "
+ list.get(x).startDate + "\n";
}
outputField.setText(temp);
}
Thanks for any help!
The constructor for employees does not initialize the instance variables, it initializes the parameters. For example, initialize the idNumber as
this.idNumber = idNumber;
Do similar statements for the remaining instance variables. This is why all the values in the employee class are null.
When testing for the idNumber, you are comparing the toString() of an employee with an idNumber. You must compare the idNumber of the employee in the list to the idNumber from the UI.
if (list.get(index).idNumber.equals(idNumber)) {
It would be better to create an accessor for each property in the employee class.
Here is the employees class with a getData method as I described in comments. (I also changed the constructor as corrected by #downyt)
class employees {
String idNumber, firstName, lastName, annualSalary, startDate;
employees(String idNumber, String firstName, String lastName, String annualSalary, String startDate) {
this.idNumber = idNumber;
this.firstName = firstName;
this.lastName = lastName;
this.annualSalary = annualSalary;
this.startDate = startDate;
}
String getData(){
return idNumber + " " + firstName + " " + lastName + " " + annualSalary + " " + startDate;
}
}
Using this method, the print code would change to something akin to this:
for (int x = 0; x < list.size(); x++){
temp = list.get(x).getData() + "\n";
}
outputField.setText(temp);
If you so desired, you could also put "\n" in getData(), changing temp to
temp += list.get(x).getData();
Related
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.
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.)
All,
Below code is working fine with the ArrayList. could you please help me on how to get user input for name gender and amountSpent (array size [4]), then split it by spaces so that it will have String, String and double.
Also, How to display the result of only the customer who has higher amount Spent then the other Customers.
thank you in advance!
Regards,
Viku
import java.util.Comparator;
public class Customer implements Comparable <Customer>{
public String name,gender;
public double amountSpent;
public Customer(String name, String gender, double amountSpent) {
super();
this.name = name;
this.gender = gender;
this.amountSpent = amountSpent;
}
public String getCustomername() {
return name;
}
public void setCoustomername(String name) {
this.name = name;
}
public String getgender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public double getamountSpent() {
return amountSpent;
}
public void setamountSpent(double amountSpent) {
this.amountSpent = amountSpent;
}
public static Comparator <Customer> CustomerNameComparator = new Comparator<Customer>() {
public int compare(Customer c1, Customer c2) {
String custName1 = c1.getCustomername().toUpperCase();
String custName2 = c2.getCustomername().toUpperCase();
//ascending order
//return custName1.compareTo(custName2);
//descending order
return custName2.compareTo(custName1);
}
};
public static Comparator <Customer> CustomerAmountSpentComparator = new Comparator<Customer>() {
public int compare(Customer aS1, Customer aS2) {
int custamtspent1 = (int) aS1.getamountSpent();
int custamtSpent2 = (int) aS2.getamountSpent();
//ascending order sort
// return custamtspent1 - custamtSpent2;
//descending order sort
return custamtSpent2 - custamtspent1;
}
};
#Override
public int compareTo(Customer o) {
return 0;
}
#Override
public String toString() {
return " Customer Name : " + name + ", Gender : " + gender + ", Amount Spent : " + amountSpent + "";
}
}
and Main Program:
import java.util.ArrayList;
import java.util.Collections;
public class MainProg {
public static void main(String args[]){
String nL = System.lineSeparator();
try {
ArrayList<Customer> arraylist = new ArrayList<Customer> ();
arraylist.add(new Customer ("Louis","Male", 4567.76));
arraylist.add(new Customer ("Daniela","Female", 7653.67));
arraylist.add(new Customer ("Jenny","Female", 3476.98));
arraylist.add(new Customer ("Arijit","Male", 9876.44));
System.out.println("Customer Name Decending Sort: " + nL);
Collections.sort(arraylist, Customer.CustomerNameComparator);
for (Customer str: arraylist) {
System.out.println(str);
}
System.out.println(nL + "Custmer Amount Spent [Hight to Low] Sorting: " + nL);
Collections.sort(arraylist, Customer.CustomerAmountSpentComparator);
for (Customer str: arraylist){
System.out.println(str);
}
System.out.println(nL + "Highest Amount Spent Custmer Detail: " + nL);
}
catch (Exception e){
System.out.println("Error: " + e);
}
finally {
System.out.println(nL + "Report Completed!");
}
}
}
OPTION 1 (suggested):
If the user is to input the data, why do you need to split it up? Just do as follows:
System.out.println("Name:");
name = scn.nextLine();
System.out.println("Gender:");
gender = scn.nextLine():
System.out.println("Amt:");
amt = scn.nextDouble();
Customer c1 = new Customer (name,gender, amt);
OPTION 2:
Alternatively, if you want user to input everything in one single line (separated by spaces), just do this:
System.out.println("Input name, gender, amt:");
name = scn.next();
gender = scn.next():
amt = scn.next();
Customer c1 = new Customer (name,gender, amt);
PROGRAM OUTPUT: Input name, gender, amt: John Male 33.50
OPTION 3 (requested by you):
Lastly if you still insist of doing a split by space, and you want to accept the user input in one string separated by spaces:
System.out.println("Input name, gender, amt:");
input = scn.nextLine();
String[] token = input.split(" ");
String name = token[0];
String gender = token[1];
double amt = Double.parseDouble(token[2]);
Customer c1 = new Customer (name,gender, amt);
PROGRAM OUTPUT: Input name, gender, amt: John Male 33.50
For your first question (if I have understood right), you want to take a user input as string:
Dave Male 123.45
and then parse this into two Strings and a double. Scanner as you mentioned is a good way to start, then try
String[] parts = input.split(" ");
double value = Double.parseDouble(parts[2]);
This will split the input into a String array of size 3 and convert the third element to a double object, that will allow you to create Customers.
For your second question, you can use a simple approach by iterating over all Customers in the ArrayList, and store the current customer with the highest amount. Replacing the customer if you find a bigger spender.
Viku, try moving
arraylist.add(new Customer(name,gender,amountSpent));
to within the
do{
...
arraylist.add(new Customer(name,gender,amountSpent));
} while(choice.equalsIgnoreCase("Yes"));
As the code is now, the arrayList.add is only executed after the loop -> only last entry.
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.