0

I want to know why the for-loop counts through the args three times and doesn't stop after the first loop? this is my code :

public class test2 {
public static void main(String[] args) {
    int N = args.length;
    int[] x = new int[N];
    int count = 0;
    for (int i = 0; i < x.length; i++) {
        x[i] = Integer.parseInt(args[i]); 
    }
    for (int i = 0; i < N; i++) {
        for (int j = i+1; j < N; j++) {
            if (x[j] != x[j-1]) {
                count++;
            }
            System.out.println(count);
        }
    }
    System.out.println(N-count);
}

}

4

1 回答 1

0

I think you mean to do this:

   for (int j = 1; j < N; j++) {
       if (x[j] != x[j-1]) {
           count++;
       }
       System.out.println(count);
   }
   System.out.println(N-count);

instead of:

for (int i = 0; i < N; i++) {
    for (int j = i+1; j < N; j++) {
        if (x[j] != x[j-1]) {
            count++;
        }
        System.out.println(count);
    }
}
System.out.println(N-count);
于 2013-10-06T22:27:34.070 回答