Java 异常处理:禁止输入字母的代码示例
public class LetterInputException extends Exception {
public LetterInputException(String message) {
super(message);
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
String input = scanner.nextLine();
if (input.matches(".*[a-zA-Z]+.*")) {
throw new LetterInputException('Input contains letters');
}
System.out.println('Input is valid: ' + input);
} catch (LetterInputException e) {
System.out.println('Error: ' + e.getMessage());
}
}
}
原文地址: https://www.cveoy.top/t/topic/jLHD 著作权归作者所有。请勿转载和采集!