2012-02-11 5 views
2

배열에 임의의 숫자를 채울 응용 프로그램을 작성하려고합니다. 내 populateArray 메서드에서 for 루프를 입력 할 때까지 모든 것이 잘 작동하는 것처럼 보입니다.자바 컴파일러가 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]); 

} 
} 

컴파일러는 (29 행에서 호출 할 때) 메소드를 분명히 입력하지만 for 루프에 도달하면 모든 실행을 중지하는 것으로 보입니다. 저는 길이가 10이기 때문에 제 루프에 적절한 초기화 및 종료 연산자가 있는지 100 % 확신합니다.

저는 솔직히 엉망입니다. 그러나 대부분의 경우와 마찬가지로 나는 매우 간단한 답변을 확신합니다. 내 결과는 다음과 같습니다.

Inputted array is length: 10 
0 //The array is not populated with numbers, so all indexes of the array return zero. 

모든 도움을 주실 수 있습니다.

답변

7

분명히 당신의 루프 테스트가이 권리라는 것을 의미합니까?

for (int i = 0; i < length; i++) { 

그렇지 않으면

, i == length 사실이 없을 것 ( length == 0하지 않는 한) 그리고 루프를 입력하지 않습니다. 당신은 또한 사용할 수도

는 :

for (int i = 0; i != length; i++) { 
0

난 당신이 루프의 조건으로 "나는 < 길이"를 작성하는 의미 생각합니다.

0

for 루프 조건은 원하는 것이 아닙니다. 나는 < 길이를 원할 것입니다.

또한 자바 컴파일러와 관련이 없습니다.

1

당신이 종료 조건에 i<=length보다는 i==length를 작성해야 ... 먼저이 0으로 변수 i을 시작하고 (귀하의 경우와 같이 i==length) 종료 상태를 확인하기 때문에, 그것은에서 입력하면이 true가 될 경우에만 루프.

+1

'<='길이로 설정하면 ArrayIndexOutOfBoundsException이 발생합니다. –

관련 문제