Broque Thomas
Broque Thomas

Reputation: 11

Why is my program not outputting my array elements?

What I am trying to do is output each element of my array to the system. Below is how the array elements were entered and my issue is beneath that. Why is it not outputting the array elements?

for (int i = 0; i <arrayLength; i++) {
    double array[] = new double[arrayLength];
    array[i] = IO.readInt("Enter number: " + (i+1));
    count++;
} 
for (int i = 0; i <arrayLength; i++) {
    System.out.println(array[i]); 
}

Upvotes: 1

Views: 92

Answers (2)

Ruslan L&#243;pez
Ruslan L&#243;pez

Reputation: 4477

You are creating a new array on each iteration so please keep the array declaration outside the loops.

double array[] = new double[arrayLength];
for (int i = 0; i <arrayLength; i++)
{
    array[i] = IO.readInt("Enter number: " + (i+1));
    System.out.println(array[i]); //reference the value saved in variable out of the for scope.
}

Upvotes: 0

Guillaume F.
Guillaume F.

Reputation: 6473

It's because you create a new array every time in the first loop. You have to declare the array before the loop.

double array[] = new double[arrayLength];

for (int i = 0; i <arrayLength; i++)
{
    array[i] = IO.readInt("Enter number: " + (i+1));
} 
for (int i = 0; i <arrayLength; i++)
{
    System.out.println(array[i]); 
}

Upvotes: 2

Related Questions