Reputation: 1
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");
}
}
}
}
Upvotes: 0
Views: 152
Reputation: 1008
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++) { ... }
Upvotes: 1
Reputation: 448
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
Upvotes: 2