Home > Back-end >  Why my java program don't run. continue take a problems
Why my java program don't run. continue take a problems

Time:10-02

can i please for help me? i don't understand why this code isn't run. under i paste my code. Thank You

class ArrayCopier2 {
public static void main(String[] arguments) {
    int[] array1 = { 7, 4, 8, 1, 4, 1, 4 };
    float[] array2 = new float[array1.length];

    System.out.print("array1: [ ");
    for (int i = 0; i < array1.length; i  ) {
        System.out.print(array1[i]   " ");
    }
    System.out.println("]");

    System.out.print("array2: [ ");
    int count = 0;
    int count2 = 0;
    while (count   <= array1.length) {
        if (array1[count] == 1) {
            continue;
        }
        array2[count2] = (float) array1[count];
        System.out.print(array2[count2  ]   " ");
    }
    System.out.println("]");
}

}

CodePudding user response:

The code runs, however, gets an ArrayIndexOutOfBoundsException. This exception occurs in your while loop:

int count2 = 0;
while (count   < array1.length) {
    if (array1[count] == 1) {
        continue;
    }
    array2[count2] = (float) array1[count];
    System.out.print(array2[count2  ]   " ");
}

This is because count returns the value before it is incremented, and you are running the loop even when the index count is the same as the array length.

So you will reach a point where the count is less than the array length (in the while loop check). Then you will add one to the count and use it as an index in the array array1[count]. This will throw an ArrayIndexOutOfBoundsException because you are trying to get an element that doesn't exist in the array.

You should increment the count variable at the end of the loop, and only run the loop while the count is LESS THAN the array length.

Solution:

class ArrayCopier2 {
    public static void main(String[] arguments) {
        int[] array1 = {7, 4, 8, 1, 4, 1, 4};
        float[] array2 = new float[array1.length];

        System.out.print("array1: [ ");
        for (int i = 0; i < array1.length; i  ) {
            System.out.print(array1[i]   " ");
        }
        System.out.println("]");

        System.out.print("array2: [ ");
        int count = 0;
        int count2 = 0;
        while (count < array1.length) {
            if (array1[count] == 1) {
                continue;
            }
            array2[count2] = (float) array1[count];
            System.out.print(array2[count2  ]   " ");
            count  ;
        }
        System.out.println("]");
    }
}

CodePudding user response:

Problem is here, array1[array1.length] is out of the range.

while (count   <= array1.length) {
    if (array1[count] == 1) {
    }
}

Do this way

while (count < array1.length) {
    ...
    count  ;
}
  • Related