I’m trying to write an application which will populate an array with random numbers. Everything seems to work fine until I try to enter the for loop in my populateArray method.
import java.util.Random;
public class PerformanceTester {
//takes an empty array, but the size must be allocated BEFORE passing
//to this function. Function takes a pre-allocated array and input size.
public static int[] populateArray(int[] inputArray, int n) {
//Create the number generator
Random generator = new Random();
int length = inputArray.length;
System.out.println("Inputted array is length: " + length);
for (int i = 0; i == length; i++) {
// for debugging purposes: System.out.println("For loop entered.");
int random = generator.nextInt((2 * n) / 3);
// for debugging purposes: System.out.println("Adding " + random + " to the array at index " + i);
inputArray[i] = random;
}
return inputArray;
}
public static void main(String[] args) {
int[] input;
input = new int[10];
int[] outputArray = populateArray(input, 10);
System.out.print(outputArray[0]);
}
}
As shown by my output, the compiler clearly enters the method (when called on line 29) but seems to stop all execution when the for loop is reached. I’m 100% sure that my loop has proper initialization and termination operators, because length is equal to ten.
I’m honestly stumped, but like most cases, I’m certain its a very simple answer. My output is below:
Inputted array is length: 10
0 //The array is not populated with numbers, so all indexes of the array return zero.
Any and all help is greatly appreciated.
Surely you meant your loop test to be this right?
Otherwise,
i == lengthwill never be true (unlesslength == 0) and it will never enter the loop.You also could have used: