当我运行我的程序时,它会将 for 循环之外的元素写入文件,但是 for 循环中的内容不会写入文件。
public static void main(String[] args) {
PrintWriter out;
try {
out = new PrintWriter("OUTPUT");
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
out.write("Participant ID Date of Data Collection Time of Data Collection HR\n");
for (Participant p : participants) {
// Write the participant information to the OUTPUT file
out.write(p.getID() + " " + p.getDate() + " " + p.getTime() + " " + " " +
p.getHR());
}
out.close();
}
}
您的代码正在运行,但正如其他人提到的那样,参与者是空的,我宁愿在 try-catch 之间编写我的所有代码
public static void main(String[] args) {
// This is only dummy data
String date = "2023/11/12";
String timeStamp = "16:30";
List<Participant> participants = List.of(
new Participant(1,date, timeStamp, 20) ,
new Participant(2,date, timeStamp, 20),
new Participant(3,date, timeStamp, 20));
try (PrintWriter out = new PrintWriter("OUTPUT")) {
out.write("Participant ID Date of Data Collection Time of Data Collection HR\n");
for (Participant p: participants) {
// Write the participant information to the OUTPUT file
out.write(p.getId() + " " +
p.getDate() + " " +
p.getTime() + " " + " " +
p.getHr() + '\n');
}
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
}
class Participant {
private int id;
private String date;
private String time;
private int hr;
public Participant(int id, String date, String time, int hr) {
this.id = id;
this.date = date;
this.time = time;
this.hr = hr;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public int getHr() {
return hr;
}
public void setHr(int hr) {
this.hr = hr;
}
}