0

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");
            }
        }   
    } 


}
2
  • You're indexing outside of the array on line 24. Don't do that. Commented Dec 7, 2017 at 7:40
  • I'd suggest you look at some Java styleguides before you get too used to these "unconventional" namings. Commented Dec 7, 2017 at 7:49

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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++) { ... }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.