I'm trying to do the following:
- Call a method that creates an
Array
with 100 randomly generated integers. - Call a method that prompts the user to enter an index position of the array and returns the value entered. If the value entered by the user is not a valid integer, throw an "Input Mismatch Exception" that prompts the user of the problem and permits them the opportunity to input a correct integer or exit the program.
package latest;
import java.util.Scanner;
import java.util.InputMismatchException;
import java.util.Random;
public class Latest
{
private static int[] randomInteger;
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int indexPosition = 0;
randomInteger = new int[100];
Random rand = new Random();
for (int i=0; i<randomInteger.length;i++)
randomInteger[i] = rand.nextInt();
while (indexPosition < 0 || indexPosition > 100)
{
try
{
// get array index position
System.out.println ("Hello, please enter an integer for the array index position: ");
indexPosition = input.nextInt();
}
catch (InputMismatchException e)
{
System.out.println ("You did not input a valid value. Please enter an Integer value between 0 and 100");
indexPosition = input.nextInt();
}
{
System.out.println ("You did not input a valid value. Please enter an Integer value between 0 and 100");
indexPosition = input.nextInt();
System.out.println (randomInteger[indexPosition]);
}
}
}
}
My problem is the code compiles but does not output anything and the IDE is saying indexPosition - "Assigned value never used"
edit: ingrid's code in the comments works perfectly if you enter a valid integer however it doesn't catch any exceptions it just crashes