Oppure

Loading
22/07/10 14:03
Bonny
Salve, ho implementato una classe Studente con interfaccia Comparable,lo studente ha come attributi : nome,cognome,matricola; grazie al metodo compareTo() e il metodo statico Collections.sort() ordino la lista in ordine alfabetico(ArrayList()) , adesso dovrei stampare la lista in un file di testo ma nnon so come fare, mi potreste aiutare? so come crare il flusso di stream ma.....
ecco il codice
package esameinfo;

import java.io.*;
import java.util.*;
import java.util.ArrayList;

public class Studente implements Comparable<Studente> {

String nome, cognome;
int metr;

public Studente(String c, String n, int m) {

this.cognome = c;
this.nome = n;
this.metr = m;
}

public int compareTo(Studente x) {

Studente p = (Studente) x;

return cognome.compareTo(p.cognome);
}

@Override
public String toString() {

return (this.cognome + " " + this.nome + " matricola " + String.valueOf(metr));
}

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

InputStreamReader in = new InputStreamReader(System.in);
BufferedReader tast = new BufferedReader(in);

List<Studente> stud = new ArrayList<Studente>();
String n, c, m;

while (true) {

System.out.println("inserire il cognome";);
c = tast.readLine();

if (c.equals("";)) {
break;
} else {

System.out.println("\ninserire il nome";);
n = tast.readLine();
System.out.println("\ninserire matricola";);
m = tast.readLine();

Studente x = new Studente(c, n, Integer.parseInt(m));
stud.add(x);
}

}
System.out.println(stud);

Collections.sort(stud);

System.out.println(stud);

Object b = stud.toArray();// è giusto cosi?? poi con fout.write(b.toString);
// nn credo sia giusto xk nn funziona.
FileWriter f = new FileWriter("out.txt";);
PrintWriter fout = new PrintWriter(f);



}
}
ho risolto il prob..
Ultima modifica effettuata da Bonny 22/07/10 17:02
aaa
28/08/10 3:59
matteo88roma
Nel tuo caso, in quanto non vedo getters per le variabili d'istanza della classe Studente, presuppongo tu voglia stampare la stringa ritornata dal metodo toString.
In quel caso:


ArrayList<Studente> studenti = new ArrayList<Studente>();
//Ammettiamo che siano stati inseriti dei valori all'interno dell'ArrayList

BufferedWriter bw = new BufferedWriter(new FileWriter("fileName"));

for (Studente s : studenti ) {
        bw.write(s.toString());
        bw.newLine();
}

bw.flush();
bw.close();



Per ulteriori informazioni: download.oracle.com/javase/6/docs/api/java/io/…

Spero di esserti stato d'aiuto :k:
aaa