题目描述 学习完异常处理后,我们可以将数据校验放在一起做。从此不必输入一个,校验一个。 这样的编程风格不好,容易打断业务流程的描述,特别是数据输入较多的时候。 请按照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 21:46:09 浏览: 163
抽象类Pet和Dog类的代码如下:
```java
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);
}
@Override
public void eat() {
System.out.println(name + " is eating");
}
@Override
public void setNameAge(String name, int age) {
if (age <= 0) {
throw new AgeException("AgeException: age cannot be " + age);
}
this.name = name;
this.age = age;
}
}
```
然后在main方法中,我们可以根据题目要求使用Scanner进行输入,如果输入的count或age不是整数,则会抛出InputMismatchException异常;如果年龄小于等于0,则会抛出AgeException异常。我们需要捕获这些异常并进行相应的处理。完整代码如下:
```java
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
```
阅读全文