0

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}

7
  • Please show us what the expected output from your method is supposed to be. It is not clear from your code, which is rife with problems. Commented Sep 3, 2021 at 4:40
  • Sorry, I'm new to java and still trying to figure it out. Commented Sep 3, 2021 at 4:47
  • I added the expected outcome Commented Sep 3, 2021 at 4:48
  • All possible return paths must return an int[]. In your code it's possible that myReader.hasNextLine() could return false. In that case, no return statement can be reached because neither the while loop nor the catch block are entered. Commented Sep 3, 2021 at 4:48
  • "The document is all numbers" - in what ways? Are they on separate lines? Separated by spaces? It's kind of difficult to suggest an accurate solution to the problem, beyond fix the obvious compiler error Commented Sep 3, 2021 at 4:56

1 Answer 1

3

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 };
}
Sign up to request clarification or add additional context in comments.

5 Comments

...but this method makes no sense, because the while loop will return after the first iteration, which almost certainly is not the logic the OP wants.
@TimBiegeleisen Since I was only asked to fix the compiler error - this is what I did. I didn't try to reason about "what" the OP was actually trying to do. If the file only contains a single line of text then if(myReader.hasNextLine()) would be more appropriate - but why are they trying to split the line they just read with a new line character?! It'd be nice to see the expected data structure of the file :P
@TimBiegeleisen I appreciate it. Like I said I'm new to Java, So I'm just feeling my way around. But I would love feed back if you have any??
@AaronCloud Well, apart from fixing your compiler error, we really can't fix the logic, because we don't have enough context. For example, you read a line of text from the file, but then try splitting the text on a new line marker ... but that won't work, because you just read the line of text, there won't be any other lines in it. Does the file contain a single line? Does it contain multiple lines? Does each line consist of just one number of a number of numbers? If so, how are the delimitated?
@MadProgrammer Your answer does fix the exact problem asked +1. Just commenting that the best answer would be to give a completely working method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.