简体   繁体   中英

Duplicates in an array invalid input

I tried making a simple code for checking in an array for duplicate numbers/numbers that are smaller than the size of the array and numbers that are bigger than the size of the array. (for example for an array by the size of 7, the number in the array should be between 1-7 with no duplicates, if not the system will print invalid error) when I enter an array by the size of 1 and enter the number 2 for example I get the following error message:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 at sumn.main(sumn.java:24)

Here is the code itself, any thoughts on how to fix this?

public class sumn {
    public static boolean Duplicates(int arr[]) {
        int a, b;
        boolean flag = true;
        for (a=0;a<arr.length-1;a++) {
            for (b=a+1;b<arr.length;b++) {
                if (arr[b]==arr[a]) {
                    return false;                       
                }               
            }
        }
        return flag;
    }

    public static void main(String[] args) {
        int N = MyConsole.readInt("Enter the size of the array:");
        int arr[] = new int [N];
        int i, j;
        boolean flag = true;
        for (i=0;i<arr.length;i++) {
            arr[i]= MyConsole.readInt("Enter a number between 1 to ");  
        }
        for (j=0;j<arr.length;j++) {
            if (Duplicates(arr)==false || N<arr[i] || arr[i]<=0) 
                flag = false;
            if (flag == false)  {
                System.out.println("Invalid input");
            }
        }   
    } 


}

Problem is in this line

if (Duplicates(arr)==false || N<arr[i] || arr[i]<=0) 

make it

if (Duplicates(arr)==false || N<arr[j] || arr[j]<=0) 

replace i with j

I'm guessing line 24 is if (Duplicates(arr)==false || N<arr[i] || arr[i]<=0) . The problem here is that after your first loop, i will have the value of arr.length . This will cause an ArrayIndexOutOfBoundsException everytime.

You can either replace i with j on that line, which seems to be what you intended to do. Or you can "clean up" a bit and scope i to only the loops by writing your loops like:

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

instead of

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

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