如何读取信息并将此信息放在对象数组中

时间:2015-04-03 20:27:40

标签: java arrays object

我有一个文件,file.txt喜欢

7 10 5  
ADD_FLIGHT SV221 Jeddah NewYork 30 7000  
ADD_FLIGHT SV223 Jeddah London 30 4000  
ADD_FLIGHT SV225 Jeddah Paris 30 3500  
ADD_FLIGHT SV227 Jeddah Cairo 30 2000  
ADD_PASS Mohammed Ali 33 M 0555788778  
ADD_PASS Sara Maghrabi 30 F 0555111111  
ADD_PASS Hani Ali 20 M 0555223344  
ADD_PASS Mohammed Hafeth 33 M 0555889876  
ADD_PASS Ahmad Sami 44 M 0555768768  
ADD_FLIGHT SV332 Jeddah Riyadh 20 500  
ADD_FLIGHT SV334 Jeddah Dammam 20 600  
ADD_FLIGHT SV367 Jeddah Dubai 25 2000  
ADD_PASS Salwa Ali 33 F 0555765672  
ADD_PASS Faisal Amri 20 M 0555111111  
ADD_PASS Mona Saleem 33 F 0555222112  
ADD_PASS Ali Ali 33 M 0555743344  
ADD_PASS Marwa Ahmad 33 F 0555545855

我想将ADD_FLIGHT之后的信息放在一个对象数组

我的代码不正确,因为setTotalSeats无法使用字符串。

如何更正代码并将航班信息放在对象数组中?

public static void inputFlight (Flight tempFlight  ) throws IOException{
     FileInputStream fstream = new FileInputStream("input.txt");
     DataInputStream in = new DataInputStream(fstream);
     BufferedReader br2 = new BufferedReader(new InputStreamReader(in));
     String strLine;
     while ((strLine = br2.readLine()) != null) {
      if(strLine.contains("ADD_FLIGHT")){
             tempFlight.setFlightCode(strLine.replace("ADD_FLIGHT",""));  
                    tempFlight.setCityFrom(strLine.replace("ADD_PASS",""));
    tempFlight.setCityTo(strLine.replace("ADD_PASS",""));
    tempFlight.setTotalSeats(strLine.replace("ADD_PASS",""));

1 个答案:

答案 0 :(得分:0)

我会将您的while循环更改为如下所示:

while ((strLine = br2.readLine()) != null) {
    if(strLine.contains("ADD_FLIGHT")){
        String[] flightInfo = strLine.split(" ");
        //first line of your example would be: {0=ADD_FLIGHT, 1=SV221, 2=Jeddah, 3=NewYork, 4=30, 5=7000}
        String flightCode = flightInfo[1];
        String cityFrom = flightInfo[2];
        String cityTo = flightInfo[3];
        int totalSeats = Integer.parseInt(flightInfo[4]);
    }
}

现在,您可以使用每个变量的内容来执行您尝试做的任何事情。