Question:
what is wrong with these java codes?
DP
2013-03-27 05:41:53 UTC
1st class:
========================================
public class FlightBooking {
public String destination, time;
public Flight[] flightNum;

public FlightBookingSystem(int i) {
Flight[] flightNum=new Flight[i];
}

public static void main(String[] args) {
FlightBooking fb = new FlightBooking(3);
fb.example();
}


public void example(){
int count=0;
flightNum[count]= new Flight("america", "5pm");
System.out.println("time: "+ flightNum[count].getTime()+"destination: "+flightNum[count].getDestination());
}
}
==================================================

2nd class:
====================================================
public class Flight {
private String destination, time;

public Flight(String destination, String time){
this.destination=destination;
this.time=time;

}

public String getDestination() {
return destination;
}

public String getTime() {
return time;
}
}
==============================================

i keep getting an error
Three answers:
Jean-Pierre Jacobs
2013-03-27 05:53:24 UTC
The problem is in your 1st class, it should look like this



1st class:

======================================…

public class FlightBooking{

public String destination, time;

public Flight[] flightNum;



public FlightBooking(int i) {

this.flightNum=new Flight[i];

}



public static void main(String[] args) {

FlightBooking fb = new FlightBooking(3);

fb.example();

}





public void example(){

int count=0;

this.flightNum[count]= new Flight("america", "5pm");

System.out.println("time: "+ this.flightNum[count].getTime()+"destination: "+this.flightNum[count].getDestination());

}

}

======================================…



First issue is that your class name an constructor is not the same



The other problem is that you didn't set you flightNum variable in you constructor, you created a local variable ALSO called flightNum and setting it to new Flight[i];



As you can see from the changes above, I added a 'this.' in front of the flightNum variable in the constructor, this is use to set the correct variable
?
2013-03-27 12:50:20 UTC
In future it would be handy if you said where the error is, and what kind of error you're getting...



But looking at it:



public FlightBookingSystem(int i) {



Should be:



public FlightBooking(int i) {





The constructor HAS to have the same name as the class.





As such, I imagine you're getting an error on the line:



FlightBooking fb = new FlightBooking(3);



As the JVM doesn't know what (3) is doing, as it can't find a constructor for the FlightBooking class.





Hope this helps!

.
JeckJeck
2013-03-27 12:55:04 UTC
I think

public FlightBookingSystem(int i) {

should read

public FlightBooking(int i) {


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...