mrbryan
mrbryan

Reputation: 5

How to use an array (and assign values to it) after it has been previously initialized?

Let's say this is my code:

public class Test {
    public static void main(String[] args) { 
        int[] text = new int[0];
        for (int i = 0; v<example.length(); i++) {
            int text[] = {maybe.indexOf(example)
        };
    }
}

How could I make it that the array inside the for loop is just overwriting the array text[] that was initialized before it? Right now I'm getting the error that Java can't find the symbol text3 in my for loop. I want to initialize the array text[] before it has all the values determined in the for loop so I can use it for the rest of my program.

Upvotes: 0

Views: 39

Answers (1)

Rick
Rick

Reputation: 576

Just write to it:

public class Test {
    public static void main(String[] args) { 
        int[] text = new int[example.length()];
        for (int i = 0; i < example.length(); i++) {
            text[i] = maybe.indexOf(example);
        }
    }
}

text[i] writes to the ith+1 place in the array (C-style arrays start counting at 0 - for complicated reasons involving memory reference locations).

Upvotes: 2

Related Questions