Java - 返回整数数组的问题

时间:2018-02-14 12:30:05

标签: java

我试图读取名为Heights.txt的.txt文件,该文件包含一个数字字符串,每个字符由":"分隔。该方法产生一个我似乎无法弄清楚的错误。

它表示"该方法必须在此代码的第一行返回int []"类型的结果。

我不明白为什么会这样说,因为integerHeightDataPoints在那时应该是一个整数数组,并且应该能够返回到int []方法?

public static int[] readFile(){
    BufferedReader br = null;
    String dataPoints;

    try { 
        br = new BufferedReader(new FileReader("Path\\Heights.txt"));
    }
    catch(IOException e) {
        System.out.println("Please enter data first");
        System.exit(0);
    }

    try {
        while((dataPoints = br.readLine()) != null) {   
            if (dataPoints.contains(":")) {
                String[] heightDataPoints = dataPoints.split(":");
                int[] integerHeightDataPoints = new int[heightDataPoints.length]; 
                for (int i = 0; i < integerHeightDataPoints.length; i++) {
                    integerHeightDataPoints[i] = Integer.parseInt(heightDataPoints[i]); 
                }
                return integerHeightDataPoints;
            }
        }
    } 
    catch (IOException e) {
        System.out.println("Error reading file");
        e.printStackTrace();
    }   
}

非常感谢所有帮助!

托马斯

1 个答案:

答案 0 :(得分:1)

这是因为当IOException永远不会触发时,你不会在第二while个案例中返回任何内容或(如提及@Exception_al)。

public static int[] readFile() {
    BufferedReader br = null;
    String dataPoints;

    try {
        br = new BufferedReader(new FileReader("/tmp/file1"));
    } catch (IOException e) {
        System.out.println("Please enter data first");
        System.exit(0);
    }
    int[] integerHeightDataPoints = new int[0];
    try {
        while ((dataPoints = br.readLine()) != null) {
            if (dataPoints.contains(":")) {
                String[] heightDataPoints = dataPoints.split(":");
                integerHeightDataPoints = new int[heightDataPoints.length];
                for (int i = 0; i < integerHeightDataPoints.length; i++) {
                    integerHeightDataPoints[i] = Integer.parseInt(heightDataPoints[i]);
                }
                return integerHeightDataPoints;
            }
        }
    } catch (IOException e) {
        System.out.println("Error reading file");
        e.printStackTrace();
    }
    return integerHeightDataPoints;
}