NullPointerException
I need help. Im getting "Exception in thread "main" java.lang.NullPointerException" error message in the following code:
package system5;
import javax.swing.*;
publicclass ArsInterface{
//public static void main(String argv[]){
//associate Arsinterface class with ARS using an instance variable
ARS system =new ARS();
AirlineCo a1 =new AirlineCo();
public ArsInterface(){}
publicvoid ARSInterface(){
this.system=new ARS();
//this.a1=new AirlineCo();? not sure if i need this
}
//}
//methods to interact with the user - one to ask user question, one to inform user of something
/** Display String */
privatevoid display(String aMessage){
JOptionPane.showMessageDialog(null, aMessage,"Electronic Address Book", JOptionPane.INFORMATION_MESSAGE);
}
/** Get User Input */
private String askUser(String aMessage){
return JOptionPane.showInputDialog(aMessage);
}
publicvoid displayMenu(){
String output, usersChoiceString;
int usersChoice;
do
{
output ="Airline Reservation System \n";
output = output +"Select a menu option \n";
output = output +"1 - Add a new airline company \n";
output = output +"2 - Display all airline companies \n";
output = output +"3 - Add a new Flight \n";
output = output +"4 - Add new passenger \n";
output = output +"5 - Remove passenger \n";
output = output +"6 - Display all flights for an Airline Co \n";
output = output +"7 - Display passengers on any flight \n";
output = output +"8 - Quit \n";
usersChoiceString = askUser(output);
//convert usersChoiceString to integer
usersChoice = Integer.parseInt(usersChoiceString);
switch (usersChoice){
case 1:
addEntry();
break;
case 2:
displayAirlineCompanies();
break;
case 3:
addFlight();
break;
case 4:
addEntryPassenger();
break;
case 5:
removeEntryPassenger();
break;
case 6:
displayFlights();
break;
case 7:
displayPassengers();
break;
case 8:
System.exit(0);
default:
output ="I did not recognise your entry ";
JOptionPane.showMessageDialog(null, output,"Error", JOptionPane.ERROR_MESSAGE);
break;
}
}while (usersChoice !=8);
}//end displayMenu method
//insert method bodies for menu options
//add the entry to the system
privatevoid addEntry(){
AirlineCo anAirlineCo;
anAirlineCo = getAirlineCompanyEntryDetails();
this.system.addEntry(anAirlineCo);
}
//get details from the user
private AirlineCo getAirlineCompanyEntryDetails(){
String airlineName;
AirlineCo newEntry;
airlineName = askUser("Please enter the name of the Airline Company");
newEntry =new AirlineCo(airlineName);
return newEntry;
}
privatevoid displayAirlineCompanies(){
String allEntries;
allEntries = this.system.allEntries();
display(allEntries);
}
//add flight details to airlineCo
privatevoid addFlight(){
Flight aFlight;
aFlight = getFlightEntryDetails();//NULLPOINTEREXCEPTION ERROR HERE
this.a1.addFlight(aFlight);
}
//get flight details from the user
private Flight getFlightEntryDetails(){
String startDest, endDest, etd, eta;
Flight newEntry;
startDest = askUser("Please enter the Departure Airport for this flight");
endDest = askUser("Please enter the destination for this flight");
etd = askUser("Please enter the Estimated Time of Departure");
eta = askUser("Please enter the Estimated Time of Arrival");
newEntry =new Flight(startDest, endDest, etd, eta);
return newEntry;
}
privatevoid addEntryPassenger(){
}
privatevoid removeEntryPassenger(){
}
privatevoid displayFlights(){
}
privatevoid displayPassengers(){
}
}//end class
I have 6 classes ARS, AirlineCo, Flight, Passenger, Standard and Business. The above class is an interface to allow the user to add airlines, flights etc.
I dont understand why the method getFlightEntryDetails is being seen as null?
Any help appreciated, cheers
[8126 byte] By [
B_Reala] at [2007-11-27 3:40:37]

i expect u to know when NullPointerException encounters,
aFlight = getFlightEntryDetails(); //NULLPOINTEREXCEPTION ERROR HERE
i belive this is not the correct place u r facing the problem, as getFlightEntryDetails() method just returns the object, either null or valid object. its purpose is that much only.
If the object u got is null and by using that 'null' reference object u might be refering to the methods/variables, that might be causing u the problem. so trace the problem properly.
Post your Flight class constructor.
Yes you are correct. The problem is in the line below
private void addFlight(){
Flight aFlight;
aFlight = getFlightEntryDetails();
this.a1.addFlight(aFlight); //NULLPOINTEREXCEPTION ERROR HERE
I think I was tweaking the program when I got the error on the above line and posted mistakenly using that error.
The flight class is as follows:
package system5;
import java.util.*;
//import javax.swing.*;
import javax.swing.JOptionPane;
import java.io.*;
public class Flight implements Serializable{
//instance variables
private String startDest, endDest, etd, eta;
TreeMap entriesPassengers;// = new TreeMap();
//filename to save data to & read data from to make Serializable
private final String FILE_NAME = "passengerBook.data";
//methods to serialize the treemap entriesPassengers (save data) and
//deserialize the treemap entriesPassengers (load data)
private void serialize(){
try{
//code that might produce an exception
//create output stream
FileOutputStream out = new FileOutputStream(FILE_NAME);
ObjectOutputStream objOut = new ObjectOutputStream(out);
//write out object, flush stream and close output
objOut.writeObject(this.entriesPassengers);
objOut.flush();
out.close();
}
catch (IOException e){
//code to execute if an exception occurs
reportError(e.toString());
}
}
private void deserialize(){
try{
//create input stream
FileInputStream in = new FileInputStream(FILE_NAME);
ObjectInputStream objIn = new ObjectInputStream(in);
//read in data and close input
this.entriesPassengers = (TreeMap) objIn.readObject();
in.close();
}
catch (IOException e){
this.entriesPassengers = new TreeMap();
}
catch (ClassNotFoundException e){
reportError (e.toString());
}
}
public Flight(){} //empty constructor
public Flight(String startDest, String endDest, String etd, String eta){
setStartDest(startDest);
setEndDest(endDest);
setEtd(etd);
setEta(eta);
//load any saved data when program starts - CHECK THIS IS RIGHT PLACE TO PUT THIS?
deserialize();
}
public String toString() {
String output;
output = "Start Destination: " + this.startDest + "\n";
output = output + "End Destination: " + this.endDest + "\n";
output = output + "Time of Departure: " + this.etd + "\n";
output = output + "Time of Arrival: " + this.eta + "\n";
return output;
}
private void reportError(String aMessage){
JOptionPane.showMessageDialog(null, aMessage, "Flight", JOptionPane.ERROR_MESSAGE);
}
private void confirmationMessage(String aMessage){
JOptionPane.showMessageDialog(null, aMessage, "Flight", JOptionPane.INFORMATION_MESSAGE);
}
//FUNCTION METHODS
public void addPassenger(Passenger aPassenger){
String message;
//check if entry with the same name already exists
if(this.entriesPassengers.keySet().contains(aPassenger.getPassenger())){
message = "An entry with the name " + aPassenger.getPassenger()+ " already exists \n";
message = message + aPassenger.getPassenger() + " has not been added";
reportError(message);
serialize();
}
else{
this.entriesPassengers.put(aPassenger.getPassenger(),aPassenger);
message = "Entry for " + aPassenger.getPassenger();
message = message + " has been added to Flight";
confirmationMessage(message);
serialize();
}
}
public void removePassenger(String aPassengerToRemove){
String message;
//check entry exists
if(entriesPassengers.keySet().contains(aPassengerToRemove)){
this.entriesPassengers.remove(aPassengerToRemove);
message = "Entry for " + aPassengerToRemove + " has been removed";
confirmationMessage(message);
serialize();
}
else{
message="Could not remove entry \n";
message= message + "There is no entry for the name " + aPassengerToRemove;
reportError(message);
}
}
public String allPassengers(){
String passengersString = "";
Passenger tempEntry;
Iterator allPassengers = this.entriesPassengers.values().iterator();
//display all elements in iterator
while(allPassengers.hasNext()){
tempEntry = (Passenger)allPassengers.next();
passengersString = passengersString + tempEntry.toString();
}
return passengersString;
}
//set methods
private void setStartDest(String startDest){
this.startDest = startDest;
}
private void setEndDest(String endDest){
this.endDest = endDest;
}
private void setEta(String eta){
this.eta = eta;
}
private void setEtd(String etd){
this.etd = etd;
}
public String getStartDest(){
return this.startDest;
}
} // end class
I have a further problem in that I need to add the flight object to a specific AirlineCo. Not sure how to do this.
I am not sure whether the class AirlineCo has addFlight(Flight obj) method. Anyway post your AirlineCo class (only required part)
Yes AirlineCo class has the addFlight method:
//FUNCTION METHODS
public void addFlight(Flight aFlight){
String message;
//check if entry with the same name already exists
if(this.entriesFlights.keySet().contains(aFlight.getStartDest())){
message = "An entry with the name " + aFlight.getStartDest()+ " already exists \n";
message = message + aFlight.getStartDest() + " has not been added";
reportError(message);
}
else{
this.entriesFlights.put(aFlight.getStartDest(),aFlight);
message = "Entry for " + aFlight.getStartDest();
message = message + " has been added to Airline Company";
confirmationMessage(message);
serialize();
}
}
Sorry for posting any unneccesary code earlier.
private void addFlight(){
Flight aFlight;
aFlight = getFlightEntryDetails();
this.a1.addFlight(aFlight); //NULLPOINTEREXCEPTION ERROR HERE
/** Get User Input */
private String askUser(String aMessage){
return JOptionPane.showInputDialog(aMessage);
}
check this function if its returning u anything
Can you check the value of entriesPassengers ? I guess it has null value.
I think entriesPassengers is null because I havent put anything in it yet, but should that matter? At the minute im just trying to add Flight objects to an Airline, and the Flight object is not null.
I think the get user input method is tight - it worked for the addEntry method which added AirlineCo to ARS.
The fear is kicking, in im so bogged down with this I cant think straight.
Is it maybe something to do with the association at the top:
//associate Arsinterface class with ARS using an instance variable
ARS system = new ARS();
AirlineCo airline;// = new AirlineCo();
when I comment the code back in to give me
//associate Arsinterface class with ARS using an instance variable
ARS system = new ARS();
AirlineCo airline = new AirlineCo();
the NullPointerException error is thrown at the addFlights(Flight obj) method in the class AirlineCo.
public void addFlight(Flight aFlight){
String message;
//check if entry with the same name already exists
if(this.entriesFlights.keySet().contains(aFlight.getStartDest())){
message = "An entry with the name " + aFlight.getStartDest()+ " already exists \n";
message = message + aFlight.getStartDest() + " has not been added";
reportError(message);
}
else{
this.entriesFlights.put(aFlight.getStartDest(),aFlight);
message = "Entry for " + aFlight.getStartDest();
message = message + " has been added to Airline Company";
confirmationMessage(message);
serialize();
}
}
But your addFlight method uses the entriesFlights. I guess this line might throw an NPE
this.entriesFlights.keySet().
Yes thats the line where the exception is thrown when I use:
AirlineCo airline = new AirlineCo();
In my ArsInterface class.
Any ideas how I go about fixing it? Im not keen on adapting the addFlight(Flight obj) method because it held water tight in my use case scenario. Should I be looking into my ArsInterface class to fix it?
Ok, Try this
private Flight getFlightEntryDetails(){
if (flightObject == null) { // here i have used flightObject. replace this with appropriate Flight object.
String startDest, endDest, etd, eta;
Flight newEntry;
startDest = askUser("Please enter the Departure Airport for this flight");
endDest = askUser("Please enter the destination for this flight");
etd = askUser("Please enter the Estimated Time of Departure");
eta = askUser("Please enter the Estimated Time of Arrival");
newEntry = new Flight(startDest, endDest, etd, eta);
return newEntry;
}
} else {
// return default flight object
}
I would not say this is a good solution :). Try this if it works implement it.
No that doesnt work. It throws up the same NPE. Thanks anyway.
I think ive sussed it. In my AirlineCo class my TreeMap entriesFlights was not initialised. However, my notes say that it doesnt need to be initialised grrrr. Im still stuck on how I add the flight objects to particular airlineCo objects tho.
Thats great! Where do you want to add the Flight Object? Post the code
In the following methods in my ArsInterface (options 1 & 3 in the menu system), the first pair add an airline company (option 1), and the second pair add the flight (option 3).
private AirlineCo getAirlineCompanyEntryDetails(){
String airlineName;
AirlineCo newEntry;
airlineName = askUser("Please enter the name of the Airline Company");
newEntry = new AirlineCo(airlineName);
return newEntry;
}
private void displayAirlineCompanies(){
String allEntries;
allEntries = this.system.allEntries();
display(allEntries);
}
private void addFlight(){
Flight aFlight;
aFlight = getFlightEntryDetails();
this.airline.addFlight(aFlight);
}
private Flight getFlightEntryDetails(){
String startDest, endDest, etd, eta;
Flight newEntryFlight;
startDest = askUser("Please enter the Departure Airport for this flight");
endDest = askUser("Please enter the destination for this flight");
etd = askUser("Please enter the Estimated Time of Departure");
eta = askUser("Please enter the Estimated Time of Arrival");
newEntryFlight = new Flight(startDest, endDest, etd, eta);
return newEntryFlight;
}
As it stands, the flights are just being added to a general ARS object I think which stores everything (airlineCo's, flights etc) and I dont think theres any relation between flights and airlines.
I think I need to put some code in the addFlight() method which asks the user to enter an airline they would like the flight added to. Something like:
private void addFlight(){
//ask user what airline co they want to add the flight to
String airlineCoToAddFlightTo;
AirlineCo airline;
airlineCoToAddFlightTo = askUser("Enter the Airline Co you would like to add the flight to");
airline = airline.getAirlineName(airlineCoToAddFlightTo); //the method getAirlineName in the type AirlineCo is not applicable for the arguments (String)
Flight aFlight;
aFlight = getFlightEntryDetails();
this.airline.addFlight(aFlight);
}
But as you can see im getting a method error.
Post your error with complete information.
The method getAirlineName() in the type AirlineCo is not applicable for the arguments (String)with the method getAirlineName() highlighted in red. It doesnt even compile.
Ok, ive modified the ArsInterface class so that now the getAirlineName() method takes an object as an argument instead of a string:
public void displayMenu(){
String output, usersChoiceString;
int usersChoice;
do
{
output = "Airline Reservation System \n";
output = output + "Select a menu option \n";
output = output + "1 - Add a new airline company \n";
output = output + "2 - Display all airline companies \n";
output = output + "3 - Add a new Flight \n";
output = output + "4 - Add new passenger \n";
output = output + "5 - Remove passenger \n";
output = output + "6 - Display all flights for an Airline Co \n";
output = output + "7 - Display passengers on any flight \n";
output = output + "8 - Quit \n";
usersChoiceString = askUser(output);
//convert usersChoiceString to integer
usersChoice = Integer.parseInt(usersChoiceString);
switch (usersChoice) {
case 1:
addEntry();
break;
case 2:
displayAirlineCompanies();
break;
case 3:
addFlight();
break;
case 4:
addEntryPassenger();
break;
case 5:
removeEntryPassenger();
break;
case 6:
displayFlights();
break;
case 7:
displayPassengers();
break;
case 8:
System.exit(0);
default:
output = "I did not recognise your entry ";
JOptionPane.showMessageDialog(null, output, "Error", JOptionPane.ERROR_MESSAGE);
break;
}
}while (usersChoice !=8);
} //end displayMenu method
//insert method bodies for menu options
//add the entry to the system
private void addEntry(){
AirlineCo anAirlineCo;
anAirlineCo = getAirlineCompanyEntryDetails();
this.system.addEntry(anAirlineCo);
}
//get details from the user
private AirlineCo getAirlineCompanyEntryDetails(){
String airlineName;
AirlineCo newEntry;
airlineName = askUser("Please enter the name of the Airline Company");
newEntry = new AirlineCo(airlineName);
return newEntry;
}
//Display all Airline Companies
private void displayAirlineCompanies(){
String allEntries;
allEntries = this.system.allEntries();
display(allEntries);
}
//Add Flight object to Airline Object
private void addFlight(){
airline = getAirlineToAddTo();
Flight aFlight;
aFlight = getFlightEntryDetails();
this.airline.addFlight(aFlight);
}
//Ask user for Airline Object to add Flight to
private AirlineCo getAirlineToAddTo(){
//ask user for the Airline they wish to add the flight to
String airlineID;
AirlineCo airlineCo;
airlineID = askUser("Please enter the name of the Airline to add the Flight to");
airlineCo = new AirlineCo(airlineID);
return airlineCo;
}
//Ask user for new Flight entry details
private Flight getFlightEntryDetails(){
String startDest, endDest, etd, eta;
Flight newEntryFlight;
startDest = askUser("Please enter the Departure Airport for this flight");
endDest = askUser("Please enter the destination for this flight");
etd = askUser("Please enter the Estimated Time of Departure");
eta = askUser("Please enter the Estimated Time of Arrival");
newEntryFlight = new Flight(startDest, endDest, etd, eta);
return newEntryFlight;
}
private void addEntryPassenger(){
}
private void removeEntryPassenger(){
}
private void displayFlights(){
//Display all Flights for a particular Airline
String allEntries;
airline = airlineToView();
allEntries = this.airline.allFlights();
display(allEntries);
}
private AirlineCo airlineToView(){
//ask user for the Airline they wish to view details for
String airlineID;
AirlineCo airlineCo;
airlineID = askUser("Please enter the name of the Airline you wish to view details for");
airlineCo = new AirlineCo(airlineID);
return airlineCo;
}
private void displayPassengers(){
}
Only when I try add a flight object to a specific airline object using the addFlight() method, its not working. The Flight objects seem to still get added to a general AirlineCo object.
How do you add more duke stars to these things... im getting desperate.
Should this be posted as a new topic seeing as the original query has been solved?
Ok this error means that the method signature in your class AirlineCo is
getAirlineName() .
but you have written the following code
airline = airline.getAirlineName(airlineCoToAddFlightTo); // remove this airlineCoToAddFlightTo parameter
or change the method signature in your AirlineCo class.
Only when I try add a flight object to a specific airline object using the addFlight() method, its not working. The Flight objects seem to still get added to a general AirlineCo object.
How do you add more duke stars to these things... im getting desperate.
Please post the exception message. Otherwise no one knows what you are saying