-3

When I run my program, it writes the elements outside of the for loop into the file however the contents in the for loop are not written to the file.

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();
    }
}
azro
  • 53,056
  • 7
  • 34
  • 70

1 Answers1

0

Your code is working but as others mentioned participants are empty and I would rather write all my code between 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;
     }
 }
DanielBarbarian
  • 5,093
  • 12
  • 35
  • 44
ARNR
  • 43
  • 4