Null objects in arrays of objects java - java

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.

Related

Making a static reference to a non-static method in another class

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.

Removing an Object from an Array of Objects in Java

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();

stack overflow error when using constructor with 2D dynamic graphic [duplicate]

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.)

Print statements with objects. Java

I am currently writing a program that models an employee as a way to get started in object oriented programming. It gets a name, hire date, and address of each employee, and then must display the information
My current program has no compile errors, but I am confused as to how I would go about printing the information in a neat manner. Thanks!
public class Unit10Assignment1
{
public static void main( String [] args )
{
int numEmployees = Input.getInt("How many employees are you storing?");
Employee database[] = new Employee[numEmployees];
for( int i = 0; i < numEmployees; i++ )
{
String firstName = Input.getString("What is an employee's first name?");
String lastName = Input.getString("What is their last name?");
String street = Input.getString("What street do they live on?");
String city = Input.getString("What city do they live in?");
String state = Input.getString("What state do they live in?(2 characters)");
String zip = Input.getString("What is their zipcode?");
int month = Input.getInt ("In what month was he/she hired?(number)");
int day = Input.getInt ("On what day was he/she hired(number)");
int year = Input.getInt ("In what year was he/she hired?(number)");
database[i] = new Employee(firstName, lastName, street, city, state, zip, month, day, year);
}
}
}
class Employee
{
Name Name;
Address Address;
Date Date;
Employee( String firstName, String lastName, String street, String city, String state, String zip, int month, int day, int year)
{
Name = new Name( firstName, lastName );
Address = new Address( street, city, state, zip );
Date = new Date( month, day, year );
}
}
class Name
{
String firstName = " ";
String lastName = " ";
public Name(String newFirstName, String newLastName)
{
firstName = newFirstName;
lastName = newLastName;
}
public String getFirst()
{
return firstName;
}
public String getLast()
{
return lastName;
}
}
class Address
{
String street = " ";
String city = " ";
String state = " ";
String zip = " ";
public Address(String newStreet, String newCity, String newState, String newZip)
{
street = newStreet;
city = newCity;
state = newState;
zip = newZip;
}
public String getStreet()
{
return street;
}
public String getCity()
{
return city;
}
public String getState()
{
return state;
}
public String getZip()
{
return zip;
}
}
class Date
{
int month = 0;
int day = 0;
int year = 0;
public Date(int newMonth, int newDay, int newYear)
{
month = newMonth;
day = newDay;
year = newYear;
}
public int getMonth()
{
return month;
}
public int getDay()
{
return day;
}
public int getYear()
{
return year;
}
}
Having trouble formatting, hopefully you can understand it. If there are any problems with my current code, pointing them out to me would be appreciated. Also, my instructor uses his own class to get user input so no need to worry about that.
For pretty printing an objects contents, I prefer overriding the toString method.
You could override the toString-method in Name, Address and Date, and let Employee use these methods in its own toString.
E.g:
Name
#Override
public String toString() {
return firstName + " " + lastName;
}
Address
#Override
public String toString() {
return street + ", " + city + ", " + state + ", " + zip;
}
Date
#Override
public String toString() {
return String.valueOf(month) + "." +
String.valueOf(day) + "." +
String.valueOf(year);
}
Employee
#Override
public String toString() {
return name.toString() + "\n" +
date.toString() + "\n" +
address.toString();
}
by the way, you can use astyle to format your code

Formatting issue when reading info into an array

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.

Categories