Thomas
Thomas

Reputation: 65

Java - Problems with returning an integer array

I'm trying to read a .txt file called Heights.txt, which contains a string of numbers, each separated by a ":". The method produces one error that I can't seem to figure out.

It says that "the method must return a result of type int[]", at the very first line of this code.

I don't understand why it says this, as integerHeightDataPoints should be an integer array at that point, and should be able to be returned to a int[] method?

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();
    }   
}

Upvotes: 1

Views: 78

Answers (1)

Farvardin
Farvardin

Reputation: 5424

It's because you don't return anything in second IOException case or (as @Exception_al mentioned) when while never triggers.

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;
}

Upvotes: 1

Related Questions