1

El problema que tengo es que necesito guardar las temperaturas de una semana en un fichero y cuando lo hago, en el fichero solo me muestra la ultima temperatura introducida.

No se donde esta el error para que me muestre todas la temperaturas.

public class Principal {

public static void introducirTempe() throws IOException {
    Scanner sc = new Scanner(System.in);
    double dias[];
    //int aux = 0;
    String diasSemana[] = {"Lunes", "Martes", "Miercoles", "Jueves", "Viernes", "Sabado", "Domingo"};
    dias = new double[7];
    for (int x = 0; x < diasSemana.length; x++) {
        System.out.println("Introduce la temperatura del " + diasSemana[x]);
        dias[0] = sc.nextDouble();

        FileWriter f = null;
        PrintWriter p = null;
        try {
            f = new FileWriter("Temperaturas.txt");
            p = new PrintWriter(f);

            for (int j = 0; j < dias.length; j++) {
                p.println(dias[j]);
            }
        }catch (IOException e) {
            System.out.println(e.getMessage());
         }finally {
            f.close();
            }
        }
    }

También dejo el main

public static void main(String args[]) throws IOException {
    Scanner sc = new Scanner(System.in);
    int opcion = -1;
    while (opcion != 0) {

        System.out.println("MENU");
        System.out.println("Selecciona una de las opciones ");
        System.out.println("1. Introducir temperatura del dia");
        System.out.println("2. Realizar estadistica");
        System.out.println("3. Salir");
        opcion = sc.nextInt();
        switch (opcion) {
            case 1:
                introducirTempe();
                break;
            case 2:
                //estadistica();
                break;
            case 3:
                //salir();
                break;
        }
    }
}
}

1 respuesta 1

2

Estás escribiendo todo el tiempo en la misma posición del array (en la posición 0):

dias[0] = sc.nextDouble();

Si tu idea es introducir la temperatura por cada día de la semana, deberías aprovechar tu variable x del bucle for para ir introduciendo temperaturas en el array:

dias[x] = sc.nextDouble();

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.