如何使用InputMismatchException对象

时间:2015-05-09 08:51:53

标签: java inputmismatchexception

我创建了一个指定大小的数组,并且必须要求用户输入索引并打印该索引值。但是,如果他们输入的内容不是int,我需要使用InputMismatchException检查他们是否已输入'q''Q'来终止我的程序。我的问题是我该怎么做。我有 catch (InputMismatchException ex)我试过if(ex == 'q'...),但我不允许这样做。我可以用什么方式测试对象?

编辑:这是我到目前为止的代码

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' )
            }
        }
    }

正如我所说,我不确定如何使用用户输入的内容

1 个答案:

答案 0 :(得分:-1)

if (ex == 'q' ) is not true, you should check  input and write 
if (input == 'q')