Skip to content
Advertisement

Returning an int array in Java

So I need a script that returns an array of a text document. The document is all numbers. Everytime I try to run it I get this message “This method must return a result of type int[]” this is under the checker part. I am trying to return it to another class so that I can use the array for if statements. Could anyone help me out with this?

import java.io.File; // Import the File class
import java.io.FileNotFoundException; // Import this class to handle errors
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Scanner; // Import the Scanner class to read text files

public class ReadFile {
public static int[] checker(){
    try {
        File myObj = new File("Tracker.txt");
        Scanner myReader = new Scanner(myObj);
        while (myReader.hasNextLine()) {
            String data = myReader.nextLine();
            String[] moreData = data.split("n");
            int day = Integer.parseInt(moreData[0]);
            int Posts = Integer.parseInt(moreData[1]);
            return new int[] {day, Posts};
        }
        
        myReader.close();
    } catch (FileNotFoundException e) {
        return new int[] {0, 0};
    }
    }

}

Expected outcome is: {0, 40}

Advertisement

Answer

The compiler is complaining because it thinks there is a possible exit path which skips all the other return statements. What happens if hasNextLine returns false on the first interaction?

In this case, you should move the return in the catch clause to the end of the method

import java.io.File; // Import the File class
import java.io.FileNotFoundException; // Import this class to handle errors
import java.util.Scanner; // Import the Scanner class to read text files

public class ReadFile {

    public static int[] checker() {
        File myObj = new File("Tracker.txt");
        // This will ensure that the Scanner is closed when
        // you exit from the loop early
        try (Scanner myReader = new Scanner(myObj)) {
            while (myReader.hasNextLine()) {
                String data = myReader.nextLine();
                // Why?  You just read the line, there
                // are no more lines in this text?!
                String[] moreData = data.split("n");
                int day = Integer.parseInt(moreData[0]);
                int Posts = Integer.parseInt(moreData[1]);
                // Why?? Are there only two values in the
                // whole file?!  Then you should use if (...) instead of while (...)
                return new int[]{day, Posts};
            }
        } catch (FileNotFoundException e) {
            // You should at least print an error   
        }
        return new int[]{0, 0};
    }

}

Have a look at The try-with-resources Statement for more information on what try (Scanner myReader = new Scanner(myObj)) { is doing

They numbers seperated by line breaks like so : 0 40 30

So, a better solution might look something like…

public static int[] checker() {
    File myObj = new File("Tracker.txt");
    List<Integer> values = new ArrayList<Integer>(128);
    try (Scanner myReader = new Scanner(myObj)) {
        while (myReader.hasNextLine()) {
            String data = myReader.nextLine();
            int value = Integer.parseInt(data);
            values.add(value);
        }
    } catch (FileNotFoundException e) {
        System.out.println("Something went wrong");
    }
    return values.stream().mapToInt(Integer::intValue).toArray();
}

The problem with using an array of this, is the fact that you don’t know how many lines (or elements) there are, so, you need something more dynamic, like a List, which you can continuously add new elements to, without needing to know how many you need to store up front.

This is a little more “advanced”, but generally, I would consider using List over arrays in most cases, but that’s me and I’m lazy.

Expected outcome is: {0, 40}

If you only want a fixed number of elements, then count the number of lines you’ve read and exit early when you’ve reached it

public static int[] checker() {
    File myObj = new File("Tracker.txt");
    try (Scanner myReader = new Scanner(myObj)) {
        int line = 0;
        int[] values = new int[2];
        while (myReader.hasNextLine()) {
            String data = myReader.nextLine();
            int value = Integer.parseInt(data);
            values[line] = value;
            line += 1;
            if (line > 1) {
                // Early exit
                break;
            }
        }
        return values;
    } catch (FileNotFoundException e) {
        System.out.println("Something went wrong");
    }
    return new int[] { 0, 0 };
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement