简体   繁体   中英

my exercise freezes and I don't understand why

I created this problem where the program looks for the duplicate number. because it does not work?

package javaapplication5;

/**
 *
 * @author miste
 */
public class JavaApplication5 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        NewClass n = new NewClass();
        int[] numero = {2, 3, 4, 5, 6, 3};
        n.cerca(numero);
    }

}

package javaapplication5;

import static java.lang.reflect.Array.get;

/**
 *
 * @author miste
 */
public class NewClass {
    int [] numero = {2, 3, 4, 5, 6, 3};

    public void cerca(int[] numero) {
        int tmp = 0;
        for (int i = 0; i < 7; i++) {
            tmp = numero[i];
        }
        for (int j = 0; j < 7; j++) {
            if (numero[j] == tmp) {
                System.out.println("il duplicato è " + tmp);
            }
        }
    }
}

Your array is of length 6. The maximum index you can iterate to is 5. Since you are iterating it from 0 to 6, it gives you an ArrayIndexOutOfBoundsExcption. You can correct it by changing the condition of the loop to i<6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM