Java返回类型是一个Object。抱怨初始化。使用try和catch的最佳方法

时间:2014-01-26 18:36:46

标签: java methods

我在一个类

中有这个公共方法
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());
   }
}

2 个答案:

答案 0 :(得分:0)

有两个schenerios,其中flightFound可能没有初始化,因此编译器坚持要初始化它。

fl.length = 0

fl [i] .getFlightNumber()!=所有数组索引中的flightNumber

答案 1 :(得分:0)

Flight flightFound是getFlight(int flightNumber)方法的本地方法,您正在初始化 尝试阻止,如果在try块中发生异常(在if之前),则控制将被转移到catch块,并且可能无法初始化flightFound。或者如果fl [i] .getFlightNumber()== flightNumber为false,则可能无法初始化flightFound。