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");
}
}
}
}
24. Don't do that.