构造一个Puppy类,该类有一个age变量保存年龄,name变量存放名字,逻辑类型的变量male表示性别(true表示性别为male,否则为female),可以通过getter方法进行访问。该类具有setAge、getAge、getName和isMale方法。 请阅读和分析裁判测试程序样例和输入输出样例,完成Puppy类的代码。import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner myScan = new Scanner(System.in); String strName = myScan.next(); String sex = myScan.next(); Puppy myPuppy = new Puppy(strName, sex.equals("male")); // 通过方法来设定age myPuppy.setAge(myScan.nextShort()); // 调用方法获取 age System.out.println("Puppy's age is : " + myPuppy.getAge()); //调用方法获取 name System.out.println("Puppy's name is : " + myPuppy.getName()); //调用方法获取性别 System.out.println("Puppy's sex is : " + (myPuppy.isMale() ? "male" : "female")); } }
时间: 2023-06-06 22:05:28 浏览: 137
使用java计算年龄
5星 · 资源好评率100%
public class Puppy {
private short age;
private String name;
private boolean male;
public Puppy(String name, boolean male) {
this.name = name;
this.male = male;
}
public void setAge(short age) {
this.age = age;
}
public short getAge() {
return this.age;
}
public String getName() {
return this.name;
}
public boolean isMale() {
return this.male;
}
}
阅读全文