我有一個指定大小的數組創建並必須要求用戶輸入索引並打印該索引值。但是,如果他們輸入的內容不是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')
}
}
}
正如我說我不知道如何使用什麼用戶輸入
請分享您的代碼 – Dude
我我添加了迄今爲止的代碼。 –
如果nextInt()不是整數,則調用next()將下一個標記作爲String,並測試該String是否等於「 q「。一個異常不是char。比較它們是沒有意義的。請注意,依賴這個異常是不好的設計。你應該使用hasNextInt()來測試下一個標記是否爲int。 –