问题 C: Revisit Pet abstract class and Dog class 时间限制: 1.000 Sec 内存限制: 128 MB 提交: 299 解决: 91 [提交] [状态] [讨论版] [命题人:外部导入]题目描述 学习完异常处理后,我们可以将数据校验放在一起做。从此不必输入一个,校验一个。 这样的编程风格不好,容易打断业务流程的描述,特别是数据输入较多的时候。 请按照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 14:45:48 浏览: 64
抽象类Pet和Dog类的代码可以如下实现:
```
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("Dog is eating");
}
public void setNameAge(String name, int age) throws AgeException {
if (age <= 0) {
throw new AgeException("AgeException: age cannot be " + age);
}
this.name = name;
this.age = age;
}
}
```
在main方法中,输入第一个数表示宠物的数量,然后循环输入每个宠物的名字和年龄。在输入年龄时,需要捕获输入类型错误和年龄异常,并输出相应的错误信息。完整的代码如下:
```
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");
}
}
}
```
阅读全文