0

我希望用户输入一串代表成绩的字母(例如 ABEDCBA 等)。

有没有办法“自定义” InputMismatchException 以便在输入 E 之后的字母时抛出该异常?还是应该用 InputMismatchException 以外的东西处理这种情况?理想情况下,我希望异常捕获 E 之后的任何字母以及任何数字/符号。那可能吗?这里是新程序员,非常感谢您的帮助!

do {
         try
         {
            System.out.print ("Please type the grades: ");
            String answerKey = Integer.toString(System.in.read());      
            exc = false; 
         }

         catch (InputMismatchException ime)
         {
            System.out.println ("You may only enter A, B, C, D, or E.");           
         }
} while (exc);
4

1 回答 1

0

您应该使用正则表达式匹配 A、B、C、D 和 E 以外的字母/符号:而且您不需要捕获 InputMismatchException 它没有意义。

System.out.print ("Please type the grades: ");
String regex = "\\b[A-E]+\\b";
if(!Integer.toString(System.in.read()).matches(regex))
{
   System.out.println ("You may only enter A, B, C, D, or E.");
}
于 2014-04-06T00:38:34.387 回答