Foros del Web » Programación para mayores de 30 ;) » Java »

escribir en un txt

Estas en el tema de escribir en un txt en el foro de Java en Foros del Web. Buenas a todos!! Por favor denme una ayudita!!! Tengo un arreglo de objeto llamado estudiante, el cual cada uno posee 4 notas, prom y me ...
  #1 (permalink)  
Antiguo 01/07/2008, 20:37
 
Fecha de Ingreso: abril-2006
Ubicación: Venezuela
Mensajes: 126
Antigüedad: 18 años
Puntos: 0
Exclamación escribir en un txt

Buenas a todos!!

Por favor denme una ayudita!!!

Tengo un arreglo de objeto llamado estudiante, el cual cada uno posee 4 notas, prom y me toca calcular la nota mayor y la nota menor. Hasta aqui voy bin y pude hacerlo sin problema. El problema es que me pide que no lo muestre por consola sino que lo guarde en un txt.


El codigo es el siguiente:

package ejercicio.datos;
class Persona {
private String nombre;
private int cedula;

public Persona (String nombre, int cedula) {
this.nombre = nombre;
this.cedula = cedula;


}

public String getNombre () {
return this.nombre;
}

public int getCedula () {
return this.cedula;
}
}



package ejercicio.datos;
public class Estudiante extends Persona {
private double Notas[];

public Estudiante (String nombre, int cedula, double Notas[]) {
super (nombre,cedula);
this.Notas = Notas;

verificarNotas();
}

private void verificarNotas () {
for (int i=0; i<this.Notas.length; i++) {
if (this.Notas[i]<0)
this.Notas[i] = 1;
}
}

public double getPromedio () {
double prom = 0;
for (int i=0; i<this.Notas.length; i++) {
prom = prom + this.Notas[i];
}
prom = prom / this.Notas.length;

return prom;
}

public double getCalificacionMasBaja () {
double nota = this.Notas[0];
for (int i=1; i<this.Notas.length; i++) {
if (nota>this.Notas[i])
nota = this.Notas[i];
}
return nota;
}
}


package ejercicio.principal;
import java.io.*;
import ejercicio.datos.Estudiante;
class Seccion {
static FileWriter archivo = null;
public static BufferedWriter bw;
public static void main (String args[]) {
String ruta = "C:/Temp/Alumnos.txt";
abrir (ruta);

/* Pedir la vantida de estudiantes
transformar esa entrada en interero
asignar a n = 5 */
/* Hacer el llamafa a las clases de lectura
* y escritura */
Estudiante estudiantes [] = new Estudiante [5];

double notaest0[]={-8,9.08,13.7,10.0};
estudiantes[0] = new Estudiante ("Patricia",15147258,notaest0);
if (bw!=null){
escribir(estudiantes[0]);
vaciarBuffer();
}
double notaest1[]={18.9,15.08,13.9,08.0};
estudiantes[1] = new Estudiante ("Williams",16000879,notaest1);
if (bw!=null){
escribir(estudiantes[1]);
vaciarBuffer();
}
double notaest2[]={15.8,19.08,12.9,05.0};
estudiantes[2] = new Estudiante ("Ines",17007521,notaest2);
if (bw!=null){
escribir(estudiantes[2]);
vaciarBuffer();
}
double notaest3[]={15.8,16.08,11.1,04.9};
estudiantes[3] = new Estudiante ("Cesar",23258147,notaest3);
if (bw!=null){
escribir(estudiantes[3]);
vaciarBuffer();
}
double notaest4[]={20.0,16.08,15.1,18.9};
estudiantes[4] = new Estudiante ("Luis",24123456,notaest4);
if (bw!=null){
escribir(estudiantes[4]);
vaciarBuffer();
}

// Nombre del estudiante con el promedio mas alto
cerrar();

Estudiante mejor = estudiantes[0];
for (int i=1; i<estudiantes.length; i++) {
if (mejor.getPromedio()<estudiantes[i].getPromedio())
mejor = estudiantes[i];
}

System.out.println("El promedio mas alto lo tiene: "+mejor.getNombre());

// Cedula del estudiante con la calificacion mas baja

Estudiante peor = estudiantes[0];
for (int i=1; i<estudiantes.length; i++) {
if (peor.getCalificacionMasBaja()>estudiantes[i].getCalificacionMasBaja())
peor = estudiantes[i];
}

System.out.println("La cedula del estudiante con la peor nota es: "+peor.getCedula() + "con nota: "+peor.getCalificacionMasBaja());

}
public static void abrir (String ruta){
try{
archivo = new FileWriter (ruta);
bw = new BufferedWriter (archivo);
}catch (IOException e){
bw = null;

}
}

public static void escribir (Estudiante S[]){
try {
bw.write(S[0]);
bw.newLine();
}catch (IOException e){
System.out.println("Error de escritura en el archivo");
}
}

public static void vaciarBuffer(){
try{
bw.flush();
}catch (IOException e){
System.out.println("Error vaciando el Buffer");
}
}

public static void cerrar (){
try{
archivo.close();
} catch (IOException e){
System.out.println("Error cerrando el archivo");
}
}

}


el problema es que cuano lo compilo me arroja el siguiente error:

escribir(estudiantes[0]); --> esto erro me sale desde el indice cero hasta el cuatro.

class java.io.BufferedWriter bw.write(S[0]);


No se me ocurre mas nada. Por favor ayudenme.

Gracias
  #2 (permalink)  
Antiguo 02/07/2008, 07:34
 
Fecha de Ingreso: junio-2008
Ubicación: Cali, Colombia
Mensajes: 74
Antigüedad: 15 años, 10 meses
Puntos: 3
Respuesta: escribir en un txt

Prueba escribiendo en el txt asi:

Cita:
try{
PrintWriter out = new PrintWriter(new File("/home/juan/prueba.txt")); //Abre el flujo de datos y escribe en el
out.write("HOLA MUNDO JAVA");
out.println();
out.close();
}catch (IOException i) {
System.out.println(i);
}
  #3 (permalink)  
Antiguo 02/07/2008, 14:14
 
Fecha de Ingreso: abril-2006
Ubicación: Venezuela
Mensajes: 126
Antigüedad: 18 años
Puntos: 0
Exclamación Respuesta: escribir en un txt

Cita:
Iniciado por maiden17 Ver Mensaje
Prueba escribiendo en el txt asi:

Hola, creo que no m explique bien. necesito es q ese arreglo de objeto donde calculo nota mayor, menor y promedio de la seccion. Escribirlo en un txt. Por favor un ayuda plis!!
  #4 (permalink)  
Antiguo 02/07/2008, 15:04
 
Fecha de Ingreso: junio-2008
Ubicación: Cali, Colombia
Mensajes: 74
Antigüedad: 15 años, 10 meses
Puntos: 3
Respuesta: escribir en un txt

Hola, intenta esto, ya es que tu le hagas las modificaciones correspondientes a la ruta de guardado del archivo.

Código:
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * 
 */
public class Seccion {
    static FileWriter archivo = null;
    public static BufferedWriter bw;
    public static void main (String args[]) {
    String ruta = "/home/juan/Alumnos.txt";
    abrir (ruta);

    /* Pedir la vantida de estudiantes
    transformar esa entrada en interero
    asignar a n = 5 */
    /* Hacer el llamafa a las clases de lectura
    * y escritura */
    Estudiante estudiantes [] = new Estudiante [5];

    double notaest0[]={-8,9.08,13.7,10.0};
    estudiantes[0] = new Estudiante ("Patricia",15147258,notaest0);
    if (bw!=null){
        escribir(estudiantes);
        //escribir(estudiantes[0]);
        vaciarBuffer();
    }
    double notaest1[]={18.9,15.08,13.9,08.0};
    estudiantes[1] = new Estudiante ("Williams",16000879,notaest1);
    if (bw!=null){
        escribir(estudiantes);
        vaciarBuffer();
    }
    double notaest2[]={15.8,19.08,12.9,05.0};
    estudiantes[2] = new Estudiante ("Ines",17007521,notaest2);
    if (bw!=null){
        escribir(estudiantes);
        vaciarBuffer();
    }
    double notaest3[]={15.8,16.08,11.1,04.9};
    estudiantes[3] = new Estudiante ("Cesar",23258147,notaest3);
    if (bw!=null){
        escribir(estudiantes);
        vaciarBuffer();
    }
    double notaest4[]={20.0,16.08,15.1,18.9};
    estudiantes[4] = new Estudiante ("Luis",24123456,notaest4);
    if (bw!=null){
        escribir(estudiantes);
        vaciarBuffer();
    }

    // Nombre del estudiante con el promedio mas alto
    cerrar();

    Estudiante mejor = estudiantes[0];
    for (int i=1; i<estudiantes.length; i++) {
        if (mejor.getPromedio()<estudiantes[i].getPromedio())
            mejor = estudiantes[i];
    }

    System.out.println("El promedio mas alto lo tiene: "+mejor.getNombre());

    // Cedula del estudiante con la calificacion mas baja

    Estudiante peor = estudiantes[0];
    for (int i=1; i<estudiantes.length; i++) {
        if (peor.getCalificacionMasBaja()>estudiantes[i].getCalificacionMasBaja())
            peor = estudiantes[i];
    }

    System.out.println("La cedula del estudiante con la peor nota es: "+peor.getCedula() + "con nota: "+peor.getCalificacionMasBaja());

    }
    public static void abrir (String ruta){
        try{
            archivo = new FileWriter (ruta);
            bw = new BufferedWriter (archivo);
        }
        catch (IOException e){
            bw = null;
        }
    }

    public static void escribir (Estudiante estudiante []){
        try {
            for(int i=0; i<estudiante.length; i++)
            bw.write(""+estudiante[i]);
            bw.newLine();
        }
        catch (IOException e){
            System.out.println("Error de escritura en el archivo");
        }
    }

    public static void vaciarBuffer(){
        try{
            bw.flush();
        }
        catch (IOException e){
            System.out.println("Error vaciando el Buffer");
        }
    }

    public static void cerrar (){
        try{
            archivo.close();
        } 
        catch (IOException e){
            System.out.println("Error cerrando el archivo");
        }
    }
}
Pruebalo y me dices

Saludos
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 02:40.