家庭作业帮助 - Java 继承和 Getters/Setters



需要一些家庭作业帮助,并且在我的控制台上有一些奇怪的输出。

这是家庭作业问题:

创建一个名为 Horse 的类,其中包含名称、颜色和出生的数据字段 年。包括这些字段的 get 和 set 方法。接下来,创建一个名为 赛马,其中包含一个附加字段,用于保存比赛数量 马匹参加过比赛以及获得和设置新领域的其他方法。 编写一个应用程序来演示如何使用每个类的对象。将文件另存为 Horse.java、RaceHorse.java和DemoHorses.java。

这是我的代码:

马.java

public class Horse {
private String name;
private String color;
private int birthYear;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getBirthYear() {
return birthYear;
}
public void setBirthYear(int birthYear) {
this.birthYear = birthYear;
}

}

赛马.java

public class RaceHorse extends Horse {
private int races;
public int getRaces() {
return races;
}
public void setRaces(int races) {
this.races = races;
}

}

演示马.java

import java.util.Scanner;
public class DemoHorses {
public static void main(String[] args) {
Horse aHorse = new Horse();
RaceHorse aRaceHorse = new RaceHorse();
String DemoName;
String DemoColor;
String RaceDemoName;
String RaceDemoColor;
int DemoYear;
int RaceDemoYear;
int DemoRace;
Scanner input = new Scanner(System.in); // Horse
System.out.print("Enter the name of the horse >> ");
DemoName = input.nextLine();
aHorse.setColor(DemoName);
System.out.print("Enter the color of the horse >> ");
DemoColor = input.nextLine();
aHorse.setColor(DemoColor);
System.out.print("Enter the birth year of the horse >> ");
DemoYear = input.nextInt();
aHorse.setBirthYear(DemoYear);
System.out.print("Enter the name of the racehorse >> "); //Racehorse
RaceDemoName = input.nextLine();
aRaceHorse.setName(RaceDemoName);
System.out.print("Enter the color of the racehorse >> ");
RaceDemoColor = input.nextLine();
aRaceHorse.setColor(RaceDemoColor);
System.out.print("Enter the birth year of the racehorse >> ");
RaceDemoYear = input.nextInt();
aRaceHorse.setBirthYear(RaceDemoYear);
System.out.print("Enter the number of races the racehorse has completed >> ");
DemoRace = input.nextInt();
aRaceHorse.setRaces(DemoRace);
System.out.println(aHorse.getName() + " is " + aHorse.getColor() + " and was born in " + aHorse.getBirthYear());
System.out.println(aRaceHorse.getName() + " is " + aRaceHorse.getColor() + " and was born in " + aRaceHorse.getRaces());
input.close();
}
}

这是我得到的输出:

Enter the name of the horse >> Old Paint
Enter the color of the horse >> black
Enter the birth year of the horse >> 2005
Enter the name of the racehorse >> Enter the color of the racehorse >> black
Enter the birth year of the racehorse >> 2222
Enter the number of races the racehorse has completed >> 12
null is black and was born in 2005
is black and was born in 12

我不知道为什么它在我的控制台上显示为Enter the name of the racehorse >> Enter the color of the racehorse >>,而且我认为用户输入的数据没有正确保存。有人知道我该如何解决这个问题吗?

添加

input.nextLine();

RaceDemoYear = input.nextInt();
aRaceHorse.setBirthYear(RaceDemoYear);

最新更新