我知道如果下一个标记与“A”匹配,Scanner.next("A")
将返回字符串“A”,否则它将抛出 InputMismatchException
。但我的代码需要采用某种方式,以便在无法从一组字符串中找到任何匹配项时抛出 InputMismatchException
。例如,如果“A”、“B”和“C”都不是下一个标记,我希望抛出 InputMismatchException
。
最佳答案
您可以使用Scanner.next(Pattern)使用正则表达式模式:
Pattern pattern = Pattern.compile("[ABC]");
myScanner.next(pattern);
甚至
myScanner.next("[ABC]");
因为,根据 Javadoc,Scanner.next(String)
An invocation of this method of the form next(pattern) behaves in exactly the same way as the invocation next(Pattern.compile(pattern)).
您甚至不必担心带有 next(String)
的版本每次都会构建一个 Pattern 对象,因为该实现维护了 Pattern 对象的缓存。
编辑:如果您要匹配的字符串不是单个字符,则正则表达式模式将有所不同:
myScanner.next("(AB|CD|EF)"); // throws for everything except AB, CD and EF.
关于java - 如果下一个标记与任何指定的字符串都不匹配,如何抛出 InputMismatchException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15315044/