Reputation: 1
I am trying to display a message after entering a series of numbers in an array and I am trying to print the array after the array limit is exceeded. The input in the array is working fine but displaying the messages after the array limit is exceeded is not working
import java.util.Scanner;
public class Array
{
public static void main (String[] args)
{
int i;
Scanner input= new Scanner(System.in);
int[] values = new int[10];
{
System.out.print("please insert a value : " );
for( i = 0 ;i < values.length; i++)
{
try
{
values[i] = input.nextInt();
}
catch (Exception e)
{
System.out.println("The value you have input is not a valid integer");
}
}
if (i> values.length)
{
System.out.println("Array limit exceeded");
for(i =0 ;i<values.length ; i++)
{
System.out.println(values[i]);
}
}
}
}
}
Upvotes: 0
Views: 596
Reputation: 56636
After this:
for( i = 0 ;i < values.length; i++)
{
try
{
values[i] = input.nextInt();
}
catch (Exception e)
{
System.out.println("The value you have input is not a valid integer");
}
}
your i
is equal to values.length
because you don't change it in the for
loop body. It will have the first integer value ( >= 0 ) that doesn't satisfy the condition and this is values.length
.
This is why the following condition is never true
:
if (i> values.length)
So, the array limit will never be exceeded.
Suggestion:
I suppose that you want something like this:
public class Array {
public static void main(String[] args) {
try (Scanner input = new Scanner(System.in)) {
int[] values = new int[10];
int i = 0;
while (true) {
System.out.print("Insert a value : ");
try {
values[i] = input.nextInt();
i++;
} catch (InputMismatchException ime) {
System.out.println("The value is not a valid integer");
input.next();
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array limit exceeded");
break;
}
}
}
}
}
If you try to add the 11th element, you will get an ArrayIndexOutOfBoundsException
.
Upvotes: 3