I’m working on a project where I have a class called Macchine (cars) and I want the user to insert a new car and then save it on a csv file.
public static void inserimento(){
List<Macchina> macchine = new ArrayList<>();
String continua;
do {
System.out.println("Inserisci i dettagli della macchina:");
System.out.print("Produttore: ");
String produttoreinput = console.readLine();
System.out.print("Modello: ");
String modelloinput = console.readLine();
System.out.print("Accelerazione (0-100 km/h in secondi): ");
String accinputstr = console.readLine();
double accinput = Double.parseDouble(accinputstr);
System.out.print("Velocità Massima (km/h): ");
String vmaxinputstr = console.readLine();
double vmaxinput = Double.parseDouble(vmaxinputstr);
System.out.print("Numero di porte: ");
String numporteinputstr = console.readLine();
int numporteinput = Integer.parseInt(numporteinputstr);
macchine.add(new Macchina(produttoreinput, modelloinput, accinput, vmaxinput, numporteinput));
System.out.print("Vuoi inserire un altro veicolo? (s/n): ");
continua = console.readLine();
} while (continua.equalsIgnoreCase("s"));
// Salva i dati nel file
try (BufferedWriter writer = new BufferedWriter(new FileWriter("macchine.txt"))) {
for (Macchina macchina : macchine) {
writer.write(macchina.toString());
writer.newLine();
}
System.out.println("I dati sono stati salvati nel file .");
} catch (IOException e) {
System.out.println("Errore durante il salvataggio dei dati: " + e.getMessage());
}
}
This is the function that handles the input and the saving.
public String toString(){
return "Produttore: " + super.getproduttore() + " Modello: " + this.getnome() + " Numero di porte: " + Integer.toString(this.getnumporte()) + " Accelerazione (0-100 km/h): " + Double.toString(super.getvmax()) +"s" + " Velocità massima: " + Double.toString(super.getacc()) +"km/h";
}
And this is the function in the class Macchina.
The problem is that when I insert a car it’s saved like in the image and I would like to have one column for each information. How can I do it?
New contributor
pepper is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.