的最好的方法,我有一個類Java返回類型是一個Object。抱怨初始化。在使用try和catch
public Flight getFlight(int flightNumber){
Flight flightFound;
try{
for (int i=0; i<fl.length; i++){
if(fl[i].getFlightNumber()==flightNumber){
flightFound= fl[i];
}
}
}catch(Exception e){
System.out.println("The object does not exist");
} finally{
return flightFound;
}
}
一個學習的過程中方法的目的,在此公開的方法,就是在傳遞給該方法的航班號返回相應的對象。什麼是錯誤檢查像try catch塊一樣? 此外,目前的方法抱怨返回flightFound可能不會被初始化。
所以我的問題是什麼是一些好的做法,返回對象,錯誤檢查,如果對象不存在?
public class Manager {
Flight[] fl;
Ticket[] ticket;
public void createFlights(){
this.fl = new Flight[5];
for (int i=0; i<5; i++){
fl[i]= new Flight();
}
this.fl[0].Flight(1030, "Toronto", "Kolkata", "03/02/14 7:50 pm", 250, 1450.00);
this.fl[1].Flight(1040, "Toronto", "Lahore", "03/02/14 7:10 pm", 250, 1450.00);
this.fl[2].Flight(1050, "Toronto", "Kolkata", "03/02/14 1:50 pm", 250, 1450.00);
this.fl[3].Flight(1060, "Toronto", "Lahore", "03/02/14 1:10 pm", 250, 1450.00);
this.fl[4].Flight(1070, "New York", "Kolkata", "03/02/14 4:50 pm", 250, 1450.00);
}
public void displayAvailableFlights(String origin, String destination){
for(int i=0; i<5; i++){
if ((this.fl[i].getOrigin().equals(origin)) &&(this.fl[i].getDestination().equals(destination))){
if (this.fl[i].getNumberOfSeatsLeft()>0){
System.out.println(this.fl[i].toString());
}
}
}
}
public Flight getFlight(int flightNumber){
Flight flightFound = new Flight();
try{
for (int i=0; i<fl.length; i++){
if(fl[i].getFlightNumber()==flightNumber){
flightFound= fl[i];
}
}
}
catch(Exception e){
System.out.println("The object does not exist");
}
finally{
return flightFound;
}
}
public static void main(String[] args){
Manager man = new Manager();
Flight flightFound = new Flight();
man.createFlights();
man.displayAvailableFlights("Toronto", "Kolkata");
flightFound=man.getFlight(030);
System.out.println(flightFound.toString());
}
}
有沒有'fl [i]'爲null的可能性? – Christian
首先,哪個方法可以在你的try塊中拋出異常?是數組'fl' null中的任何'Flight's?如果是這樣,你應該檢查空值而不是讓代碼拋出(所以你根本不需要try/catch)。然後,如果航班號未找到,您應該決定如何處理:返回null或拋出異常是選項。最後,你並不需要'finally'塊。 –
還有一件事。使用原始數組是可以的,但您會發現[Java集合](http://docs.oracle.com/javase/tutorial/collections/)功能更強大,並提供了許多方法來組織對象。 –