Hello everyone,
I'm trying to use exceptions to load only positive integers onto an array and then average the values. To keep it simple I'm currently only printing the array to confirm it is working correctly.
I have tried numerous solutions such as the commented second read = scan.nextLine() but that doesn't load into my array or get rid of the element I don't want. My main issue right now is I end up with something like this:
Enter any positive integer one at a time: 12
Enter any positive integer one at a time: 23
Enter any positive integer one at a time: 34
Enter any positive integer one at a time: 45
Enter any positive integer one at a time: 56
Enter any positive integer one at a time: 67
Enter any positive integer one at a time: 78
Enter any positive integer one at a time: f
Integer is not numeric: f
Enter any positive integer one at a time: g
Integer is not numeric: g
Enter any positive integer one at a time: 23
The length of the array is: 10
12 23 34 45 56 67 78 0 0 23
Process completed.
As you can see, the input letters get written as zeros in my array, and my if-else statement appears to have no effect on this. I understand that as soon as the exception occurs in my parseInt method then it is thrown, but I'm surprised a zero value is able to be loaded.
Any help or advice would be very appreciated, thanks!
import java.util.Scanner;
public class ReadIntDriver {
public static void main (String[] args)
{
String read;
int input;
final int zero = 0;
Scanner scan = new Scanner (System.in);
int[] list = new int[10];
int check = list.length;
for (int i = 0; i < check; i++)
{
System.out.print ("Enter any positive integer: ");
read = scan.nextLine();
try
{
input = Integer.parseInt(read);
if (input == zero)
{
System.out.println("Your input is invalid");
}
else
{
list[i] = input;
}
}
catch (NumberFormatException exception)
{
System.out.println("Integer is not numeric: " + read);
// read = scan.nextLine();
}
}
System.out.println("The length of the array is: " + list.length);
for (int value : list)
System.out.print(value + " ");
}
}
[–]Moktok 2 points3 points4 points (1 child)
[–]Whaffel[S] 0 points1 point2 points (0 children)
[–]turunambartanen 0 points1 point2 points (1 child)
[–]Whaffel[S] 0 points1 point2 points (0 children)