狗的年龄只能增加一岁,不能减少。我的代码仍然有错误,说年龄没有增加。
public class Dog {
private String name;
private String breed;
private int age;
private int weight;
private double tailLength;
private static final double TAIL_LENGTH_FOR_DACHSHUND = 3.7;
public Dog(String name, String breed, int age, int weight) {
this.name = name;
this.breed = breed;
this.age = age;
this.weight = weight;
this.tailLength = tailLength;
normalLetters();
}
public String getName() {
return name;
}
public String getBreed() {
return breed;
}
public int getAge() {
return age;
}
public void setAge(int newAge) {
if (newAge > this.age) {
this.age = newAge;
} else {
System.out.println("Age cannot decrease. Keeping the current age.");
}
}
public int getWeight() {
return weight;
}
private void setWeight(int weight) {
this.weight = weight;
}
public double getTailLength() {
if (breed.toLowerCase().equals("tax") || breed.toLowerCase().equals("dachshund")) {
return TAIL_LENGTH_FOR_DACHSHUND;
} else {
return (age * weight) / 10.0;
}
}
private void setTailLength(double tailLength) {
this.tailLength = tailLength;
}
private void normalLetters() {
this.name = normalString(this.name);
this.breed = normalString(this.breed);
}
private String normalString(String input) {
return input.toUpperCase();
}
public String toString() {
return name + breed + age + weight + tailLength;
}
}
我已经找到了与我已有的解决方案类似的其他解决方案,但没有一个有效。另外,第二次我删除了我已经拥有的那个,它显示测试中存在更多错误,表明年龄没有增加。
像这样尝试一下。不需要错误消息等。根据需要更改方法的名称。
public void updateAge() {
this.age++;
}