2015-05-09 123 views
-1

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

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

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

正如我说我不知道​​如何使用什么用户输入

+0

请分享您的代码 – Dude

+0

我我添加了迄今为止的代码。 –

+2

如果nextInt()不是整数,则调用next()将下一个标记作为String,并测试该String是否等于“ q“。一个异常不是char。比较它们是没有意义的。请注意,依赖这个异常是不好的设计。你应该使用hasNextInt()来测试下一个标记是否为int。 –

回答

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

我试过了,但我得到一个错误,说扫描仪和字符不兼容 –

+0

试试这个String.valueOf(input.nextLine()。charAt(0))=='q' – fasadat