aer*_*lve 2 java loops for-loop
我正在尝试编写一个应用程序,它将使用随机数填充数组.在我尝试在populateArray方法中输入for循环之前,一切似乎都能正常工作.
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]);
}
}
Run Code Online (Sandbox Code Playgroud)
如我的输出所示,编译器清楚地输入方法(当在第29行调用时)但似乎在达到for循环时停止所有执行.我100%确定我的循环有正确的初始化和终止操作符,因为长度等于10.
老实说,我很难过,但大多数情况下,我确定这是一个非常简单的答案.我的输出如下:
Inputted array is length: 10
0 //The array is not populated with numbers, so all indexes of the array return zero.
Run Code Online (Sandbox Code Playgroud)
非常感谢任何和所有的帮助.
当然,你的意思是你的循环测试是正确的吗?
for (int i = 0; i < length; i++) {
Run Code Online (Sandbox Code Playgroud)
否则,i == length永远不会是真的(除非length == 0),它永远不会进入循环.
您也可以使用:
for (int i = 0; i != length; i++) {
Run Code Online (Sandbox Code Playgroud)