学习完异常处理后,我们可以将数据校验放在一起做。从此不必输入一个,校验一个。 这样的编程风格不好,容易打断业务流程的描述,特别是数据输入较多的时候。 请按照Main类及输出案例 1. 编写抽象类Pet,包含构造方法, 抽象方法eat和setNameAge及成员变量:name, age; 2. 编写Dog类(Pet类的子类)。 3. 编写AgeException异常类,当年龄不大于零,抛出该类异常(Dog类中的setNameAge方法中抛异常, 输出:AgeException: age cannot be this.age)。 import java.util.*; public class Main { public static void main(String[] args) { Scanner r = new Scanner(System.in); int count; try { count = r.nextInt(); Pet petList[] = new Pet[count]; for(int i=0;i<count;i++) { String name; int age; petList[i] = new Dog(); name = r.next(); age = r.nextInt(); petList[i].setNameAge(name, age); petList[i].eat(); } } catch(AgeException e) { System.out.println(e); } catch(InputMismatchException e) { System.out.println(e+ ": count or age must be an integer"); } catch(Exception e) { System.out.println(e+": other exception"); } } } 样例输入 4a aa 11 bb 22 cc 33 dd 44 样例输出 java.util.InputMismatchException: count or age must be an integer
时间: 2023-12-03 11:46:01 浏览: 83
Spring Boot 数据校验@Valid+统一异常处理的实现
以下是代码实现:
```
import java.util.*;
abstract class Pet {
protected String name;
protected int age;
public Pet(String name, int age) {
this.name = name;
this.age = age;
}
public abstract void eat();
public abstract void setNameAge(String name, int age);
}
class Dog extends Pet {
public Dog() {
super("", 0);
}
public void eat() {
System.out.println(name + " is eating.");
}
public void setNameAge(String name, int age) {
if (age <= 0) {
throw new AgeException("AgeException: age cannot be " + age);
}
this.name = name;
this.age = age;
}
}
class AgeException extends RuntimeException {
public AgeException(String message) {
super(message);
}
}
public class Main {
public static void main(String[] args) {
Scanner r = new Scanner(System.in);
int count;
try {
count = r.nextInt();
Pet petList[] = new Pet[count];
for (int i = 0; i < count; i++) {
String name;
int age;
petList[i] = new Dog();
name = r.next();
age = r.nextInt();
petList[i].setNameAge(name, age);
petList[i].eat();
}
} catch (AgeException e) {
System.out.println(e);
} catch (InputMismatchException e) {
System.out.println(e + ": count or age must be an integer");
} catch (Exception e) {
System.out.println(e + ": other exception");
}
}
}
```
输入样例:
```
4a aa 11 bb 22 cc 33 dd 44
```
输出样例:
```
java.util.InputMismatchException: count or age must be an integer
```
阅读全文