"For each not applicable to type" error solution

Viewed 30

Beginner. I'm trying to write a program to take a collection of objects and serialize them into a .csv file. I understand that I can't use "for each" to iterate through objects, but the solution I found still isn't solving. Help much appreciated.

Code (entity class):

 package com.example.baby;
 import java.io.IOException;
 import java.io.BufferedWriter;
 import java.nio.charset.Charset;
 import java.nio.file.Files;
 import java.nio.file.Path;
 import java.nio.file.Paths;
 import java.nio.file.StandardOpenOption;

 public class Baby {

     private String name;
     private String gender;
     private String eyeColor;
     //private Iterable<? extends Baby> to_char_array;


     public Baby()
     {
         name = "";
         gender = "";
         eyeColor = "";
     }

     public Baby(String name, String gender, String eyeColor) {
         this.name = name;
         this.gender = gender;
         this.eyeColor = eyeColor;
     }

     public static void serializeAsCSV(String path, Baby babies) throws IOException {
         Path filePath = Paths.get(path);
         try(BufferedWriter buffer = Files.newBufferedWriter(filePath,
                 Charset.defaultCharset(), StandardOpenOption.APPEND)) {
             buffer.newLine();
             for(Baby baby:babies){
                 buffer.append(baby.prettyPrintCSV());
                 buffer.newLine();
             }
         }

     }
     private String prettyPrintCSV(){
         return name + ", " + gender + ", " + eyeColor; //method i will call inside serialize
     }

Code (driver class):

package com.example.baby;
 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.List;

 public class baby_project {

     public static void main(String[] args) throws IOException {

         Baby baby = new Baby();
         Baby.serializeAsCSV("babies.csv",
                 new Baby("Donald", "Male", "Brown"));
         List<String> lines = new Baby().serializeAsCSV("babies.csv");
         System.out.println(lines.get(0));
     }
 }
0 Answers
Related