我正在我的项目中工作,涉及一家诊所,我的班级是预约,我必须让用户输入日期,时间,科,医生姓名,患者姓名。并存储一个ArrayList 我写了代码,但是当我运行项目时,没有输出,我也不知道为什么:(
package appointments;
import java.util.Scanner;
import java.util.ArrayList;
public class Appointment {
public static void main(String[] args) {
ArrayList<Object> appointments = new ArrayList<>();
Scanner input = new Scanner (System.in);
System.out.println("enter day, time, section , doctor , you name in order to book appointment : ");
appointment xx = new appointment();
for (int i=0; i<5; ++i)
xx.setAppDay(input.nextLine());
xx.setAppTime(input.nextLine());
xx.setAppSection(input.nextLine());
xx.setAppDoctor(input.nextLine());
xx.setAppPatient(input.nextLine());
appointments.add(xx);
System.out.println(appointments);
}
public static class appointment {
public String appDay;
public String appTime;
public String appSection;
public String appDoctor;
public String appPatient;
public appointment(String appDay, String appTime, String appSection, String appDoctor, String appPatient) {
this.appDay = appDay;
this.appTime = appTime;
this.appSection = appSection;
this.appDoctor = appDoctor;
this.appPatient = appPatient;
}
public appointment() {
}
public void setAppDay(String appDay) {
this.appDay = appDay;
}
public void setAppTime(String appTime) {
this.appTime = appTime;
}
public void setAppSection(String appSection) {
this.appSection = appSection;
}
public void setAppDoctor(String appDoctor) {
this.appDoctor = appDoctor;
}
public void setAppPatient(String appPatient) {
this.appPatient = appPatient;
}
public String getAppDay() {
return appDay;
}
public String getAppTime() {
return appTime;
}
public String getAppSection() {
return appSection;
}
public String getAppDoctor() {
return appDoctor;
}
public String getAppPatient() {
return appPatient;
}
}
}
答案 0 :(得分:0)
您的循环没有花括号,并且您仅实例化一个appointment
。您想要类似的东西,
for (int i = 0; i < 5; ++i) {
appointment xx = new appointment();
xx.setAppDay(input.nextLine());
xx.setAppTime(input.nextLine());
xx.setAppSection(input.nextLine());
xx.setAppDoctor(input.nextLine());
xx.setAppPatient(input.nextLine());
appointments.add(xx);
}
然后,您需要覆盖toString()
中的appointment
。
答案 1 :(得分:0)
当前将同一约会对象添加到列表中,因此列表中将只有一个条目。
因此将对象的创建和添加移动到列表中,并在for循环内设置约会字段。请正确添加大括号,因为当前仅 xx.setAppDay(input.nextLine()) 是for循环的一部分。
约会也不应该是静态类,需要创建多个对象。
答案 2 :(得分:-1)
为此,您需要实现toString()方法。然后像这样打印。
public String toString(){
return this.appDay; // return the output you want, so build a String using your attributes
}
System.out.println(Arrays.toString(appointments));
编辑:按照Elliott Frisch所说的做。