dimmed
dimmed

Reputation: 47

adding values on array java

i don't know what's wrong. the array should be in Number or int.

here's my code:

Number[] freq;

    int place = 0;

    BufferedReader br = new BufferedReader(new FileReader(new File("this.txt")));

    String read;

    String[] temp;

    int num;

    while((read = br.readLine())!=null)
    {
        temp = read.split(",");
        for(int i = 0; i<=temp.length; i++)
        {
            String t = temp[i];
            num = Integer.parseInt(t);
            freq[place] = num;
            place++;
        }

    }

    System.out.println("done");

it shouldn't output some heavy result but i need it working. i always get the error

variable freq might not have been initialized.
freq[place] = num;

Upvotes: 0

Views: 64

Answers (3)

Erik
Erik

Reputation: 3636

You need to set a size for the Array. Since you indicated in the comments that it has to be dynamic, you'll have to instead use a different kind of variable that can be used with dynamic length, such as an ArrayList.

See this example:

// initialize an ArrayList:
List<Number> freq = new ArrayList<Number>();
BufferedReader br = new BufferedReader(new FileReader(new File("this.txt")));

String read;
String[] temp;

int num;

while((read = br.readLine())!=null)
{
    temp = read.split(",");
    for(int i = 0; i<=temp.length; i++)
    {
        String t = temp[i];
        num = Integer.parseInt(t);
        freq.add( num );
    }

}

System.out.println("done");

Upvotes: 2

Harry
Harry

Reputation: 3205

You need to set an array size before you use an array in JAVA.

int[] someArray= new int[size]

Upvotes: 0

Jan Groth
Jan Groth

Reputation: 14686

You must initialise the array.

Number[] freq = new Number[someSize]

Upvotes: 3

Related Questions