I'm working on a project where I have a class called dog and I want the user to insert a new dog and then save it on a csv file.
public static void insert(){
List<Dog> dogs = new ArrayList<>();
String c;
do {
System.out.println("Insert new dog:");
dogs.add(new Dog());
System.out.print("Do you want to continue? (y/n): ");
c = console.readLine();
} while (c.equalsIgnoreCase("y"));
try (BufferedWriter writer = new BufferedWriter(new FileWriter("macchine.txt"))) {
for (Dog dog : dogs) {
writer.write(macchina.toString());
writer.newLine();
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
How can I do it?
Modify your toString function like this:
public String toString(){
return super.getproduttore() + ";" + this.getnome() + ";" + Integer.toString(this.getnumporte()) + ";" + Double.toString(super.getvmax()) +";" + Double.toString(super.getacc()) ;
}
and provide an header row like this:
String header = "Produttore;Modello;Numero di porte;Accelerazione(0-100 km/h);Velocità massima (km/h)";
write this row to .csv (change .txt with .csv) file before for loop
writer.write(header);
for (Macchina macchina : macch...