Why am I getting this error:
Please Enter 5 variables:
Please enter value in slot 0:1
Please enter value in slot 1:2
Please enter value in slot 2:5
Please enter value in slot 3:4
Please enter value in slot 4:2
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at Duplicates.NumberCheck(Duplicates.java:32)
at Duplicates.main(Duplicates.java:48)
= 5
I have played around with the limits, and changed around a few other things, but I can't seem to get around this error! Here's the rest of my code:
import java.util.*;
public class Duplicates
{
Scanner input = new Scanner( System.in );
int i;
int cnt = 0;
int numbers[] = new int[5];
public void EnterNumbers()
{
System.out.println("Please Enter 5 variables: ");
for (i=0; i<=4; i++)
{
System.out.printf("Please enter value in slot " + i + ":");
numbers[i] = input.nextInt();
cnt++;
}
System.out.printf(" = " + cnt);
}
public void NumberCheck()
{
for (int j=0; j<=cnt-1; j++)
{
if (numbers[j] == numbers[cnt])
{
System.out.println("Repeated Number");
}
else
{
System.out.println(cnt + " = " + numbers[cnt]);
}
}
}
public static void main(String[] args)
{
Duplicates DuplicateTest = new Duplicates();
DuplicateTest.EnterNumbers();
DuplicateTest.NumberCheck();
}
}