从文件输入创建对象的Java问题

时间:2019-05-11 19:13:46

标签: java object fileinputstream

我是Java编程的新手,我的代码遇到了一些问题。 我有一个文件管理器类,用于从文件获取输入。

创建对象后,我从另一个类调用了一个方法以将其存储在数组中。但似乎它没有存储到数组中。

FileManager.java

try {
            fileStrm = new FileInputStream(inFilename);
            rdr = new InputStreamReader(fileStrm);
            bufRdr = new BufferedReader(rdr);
            line = bufRdr.readLine();
            while( line != null){
                lineArray = line.split("\\,");

                serialNum = validateSerialNum(lineArray[0]);
                year = validateYear(Integer.parseInt(lineArray[1]));         
                hull = validateHull(lineArray[2]);
                maxDepth = validateMaxDepth(Double.valueOf(lineArray[3]));

                inSubmarine = new Submarine(serialNum, year, maxDepth, hull);
                inShipStorage.addSubmarine(inSubmarine);

                line = bufRdr.readLine();    
            }
            fileStrm.close();
        }
         catch (IOException e) {
            System.out.println("Error in file processing: " + e.getMessage());
        }
    }

创建海底物体

public Submarine(String inSerialNum, int inYear, double inMaxDepth, String inHull)
    {   
            serialNum = inSerialNum;
            year = inYear;
            maxDepth = inMaxDepth;
            hull = inHull;
   }

ShipStorage.java

    public ShipStorage() {
        submarineArray = new Submarine[maxSub];
        fighterJetArray = new FighterJet[maxJet];
        countJet = 0;
        countSub = 0;
    }

将对象添加到数组

   public void addSubmarine(Submarine inSubmarine) {
        if (countSub < maxSub && inSubmarine != null) {
            submarineArray[countSub] = new Submarine(inSubmarine);
            System.out.println("Submarine added succesfully!");
            countSub += 1;
        } else {
            throw new IllegalArgumentException("no submarine object");
        }
    }

testInput.txt

111.111,2019,steel,-400.0

viewShip方法

public void viewShip()
{
int x = 0;
       for (int i = 0; i < countSub; i++) {
            if (submarineArray[i] != null) {
                 System.out.println(submarineArray[i].toString());
            }
        }
 }

这是我的结果

> C:\Users\plast\Desktop\Worksheet 8>java ShipManager 
Pls select a function:
>  1. Add Submarine
>  2. Input File
>  3. Check Duplicate
>  4. View Ships
>  5. Exit 
3 
>  Input file: 
testInput.txt 
>Submarine added successfully! 
Pls select a function:
>  1. Add Submarine
>  2. Input File
>  3. Check Duplicate
>  4. View Ships
>  5. Exit 
6 
Pls select a function:
>  1. Add Submarine
>  2. Input File
>  3. Check Duplicate
>  4. View Ships
>  5. Exit 

如果正确存储了潜艇和战斗机,则viewShip方法应该能够显示可用的舰船

0 个答案:

没有答案