I have an array of a specified sized created and must ask the user to enter an index and print that indexed value. However if they enter something that's not an int I need to use an InputMismatchException
to check whether they've entered 'q'
or 'Q'
to terminate my program. My question is how do I do this. I have
catch (InputMismatchException ex)
and I've tried if(ex == 'q'...)
but I'm not allowed to do this. In what way can I test the object?
EDIT: This is the code I have so far
import java.util.InputMismatchException;
import java.util.Scanner;
public class ExceptionsWithUserInput {
public static void main(String[] args) {
final int SIZE_OF_ARRAY = 100;
final int MAX_OF_ARRAY = 10;
final int MIN_OF_ARRAY = -10;
float [] randomFloats = new float [SIZE_OF_ARRAY];
for (int i = 0; i < SIZE_OF_ARRAY; i++){
randomFloats [i] = (float) ((Math.random () * 10) - 10);
}
Scanner input = new Scanner (System.in);
System.out.println("Generating 100 random numbers in [-10.0,10.0) ...");
boolean continueInput;
do {
try {
System.out.print ("Please enter an index: ");
int index = input.nextInt();
System.out.println(
"The random number for index = " + index + " is "
+ randomFloats[index]);
continueInput = true;
}
catch (IndexOutOfBoundsException ex){
System.out.println("ERROR: user-supplied index is out of bounds!");
continueInput = true;
}
catch (InputMismatchException ex){
if (ex == 'q' )
}
}
}
As I was saying I'm not sure how to use what the user inputs