使用java 语言写一段代码定义一个异常类当输入的字符串是字母时将产生异常 并写try-catch 方法解决
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/cfYD 著作权归作者所有。请勿转载和采集!