Hey everyone, I have a quick question about some Java code.
I need to write a method that fills an array, with a few conditions.

The method I'm writing is called readArray.
There are two arrays, one called "states" and the other "capitals". I have to fill both these String arrays using ONE method. I can handle that, except I have to fill them using information from a file. The first line in the file is a state, the second is it's the capital...and so on. Do I create the arrays in the main method and pass them to readArray as parameters? Or do I create the arrays inside of the readArray?

I am completely lost with this. Can someone help? Thanks :)

Dani AI

Generated

Brief summary and recommendation: both approaches mentioned in the thread work. is right that passing arrays into a method lets that method fill them and return a single int indicating how many pairs were stored. 's suggestion of class-level arrays also works, but it ties state to a broader scope and reduces modularity. The most robust option is to read pairs of lines into dynamic lists (ArrayList) so the file size does not need to be guessed; convert to arrays afterward only if the rest of the program requires them.

Example that fills caller-provided arrays and returns the number stored:

public static int readArray(Path path, String[] states, String[] capitals) throws IOException {
    try (BufferedReader br = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
        int i = 0;
        String state;
        while (i < states.length && (state = br.readLine()) != null) {
            String capital = br.readLine();
            if (capital == null) capital = ""; // decide how to handle odd-numbered files
            states[i] = state.trim();
            capitals[i] = capital.trim();
            i++;
        }
        return i;
    }
}

Alternative using dynamic lists (recommended when file length is unknown):

List<String> states = new ArrayList<>();
List<String> capitals = new ArrayList<>();
try (BufferedReader br = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
    String state;
    while ((state = br.readLine()) != null) {
        String capital = br.readLine();
        if (capital == null) capital = "";
        states.add(state.trim());
        capitals.add(capital.trim());
    }
}
String[] statesArr = states.toArray(new String[0]);
String[] capitalsArr = capitals.toArray(new String[0]);

Notes and pitfalls: check for ArrayIndexOutOfBounds when using fixed arrays; decide policy for blank or odd trailing lines (skip, empty string, or throw); always close readers (try-with-resources) and pick correct charset; if a mapping from state to capital is preferred, use a LinkedHashMap<String,String> to preserve file order.

Recommended Answers

All 4 Replies

best would be to create the arrays on class level, not within a method. that way, you don't have to pass them as parameters, and still use them within several methods.

do you know up front how many elements the files have? if so, instantiate the arrays when you declare them, otherwise, instantiate them within the method filling the values.

In java you can only return one thing from a method. You can't return two arrays (unless you package both those arrays inside a single object and return that, which is probably a bit excessive for this case).
However, when someone passes an array into a method as a parameter, you can access, use, or update the elements of that array. And because you can have any number of parameters, you can update any number of arrays like that.
So create two arrays in main, pass them as parameters to your readArray method, and store all your states and capitals in the arrays you were passed.
Since main doesn't know how big the file is, you'll just have to create two arrays that are "big enough" and maybe have readArray return a single int that says how many states/capitals have been stored in them.

ps: Stultuske's post came in while I was typing. Between us we have given you two approaches, both equally valid. It probably doesn't matter which you chose, but you may find his easier as a beginner. In any case you should understand the stuff I was explaining about parameters and return values.

In java you can only return one thing from a method. You can't return two arrays (unless you package both those arrays inside a single object and return that, which is probably a bit excessive for this case).
However, when someone passes an array into a method as a parameter, you can access, use, or update the elements of that array. And because you can have any number of parameters, you can update any number of arrays like that.
So create two arrays in main, pass them as parameters to your readArray method, and store all your states and capitals in the arrays you were passed.
Since main doesn't know how big the file is, you'll just have to create two arrays that are "big enough" and maybe have readArray return a single int that says how many states/capitals have been stored in them.

ps: Stultuske's post came in while I was typing. Between us we have given you two approaches, both equally valid. It probably doesn't matter which you chose, but you may find his easier as a beginner. In any case you should understand the stuff I was explaining about parameters and return values.

Actually that makes complete sense. Thanks!
One other quick question. Is there a way to fill an array with every other line from the file?

Just write a loop that reads two two lines on each iteration, and does nothing with one of them!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.