-1

我创建了一个指定大小的数组,并且必须要求用户输入索引并打印该索引值。但是,如果他们输入不是 int 的内容,我需要使用 anInputMismatchException检查他们是否输入'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' )
            }
        }
    }

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

4

1 回答 1

-1
if (ex == 'q' ) is not true, you should check  input and write 
if (input == 'q') 
于 2015-05-09T09:00:50.097 回答