docenciait / ProgramacionDAW

0 stars 0 forks source link

Null al cargar HashMaps como atributos de la clase #20

Closed javierbarbe closed 4 years ago

javierbarbe commented 4 years ago

Buenas Ivan La duda de hoy va sobre HashMaps y leer archivos... el caso es que al ejecutar el siguiente codigo... me da como que el array que inicializo como atributo esta vacio... y no deberia...

package nuevisimo;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Scanner;

public class Pregunta {
    Scanner sc = new Scanner(System.in);
    String[] categorias = { "arte", "ciencia", "literatura", "cine", "historia" };
    HashMap<String, String> tacoPreguntas = new HashMap<>();
    HashMap<String, String> pregNombres = new HashMap<>();
    HashMap<String, String> pregLugares = new HashMap<>();

    int contadorPreguntasNombres=0;
    {
        try {
            BufferedReader br = new BufferedReader(new FileReader("trivial/nuevisimo/preguntasYrespuestas.txt"));
            String linea = "";
            String respuesta = "";
            while (linea != null) {

                linea = br.readLine();
                respuesta = br.readLine();
                if (linea != null) {
                    pregNombres.put(linea, respuesta);
                }
            }
        } catch (FileNotFoundException e) {
            System.out.println("no se encontro el archivo de preguntas respuestas de historia");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            System.out.println("error al leer del archivo");
        }String [] preguntasNombres= pregNombres.entrySet().toArray(new String [0]);
    }
    String categoria;
    public void leerPreguntas() {
        for (String i : preguntasNombres) {
            System.out.println(i);
        }
    }

    public void preguntar(String categoria) {

        if (categoria.equals("nombres")) {
            String pregunta= pregNombres.get(preguntasNombres[contadorPreguntasNombres]);
            System.out.println("Respuesta?");
            String respuesta = sc.nextLine();
            if(respuesta.equalsIgnoreCase(pregNombres.get(pregunta))){
                System.out.println("respuesta correcta");
            }
            else {
                System.out.println("nooooooooooooooooooooo incorrecto");
            }
        }
    }
public static void main (String [] args) {
    Pregunta t1 = new Pregunta();
    t1.leerPreguntas();
    //t1.preguntar("nombres");
}
}
javierbarbe commented 4 years ago

mmm ... vale ya lo solucioneee gracias igualmente!!

ivanjimenez commented 4 years ago

Perfecto, pero la próxima vez que haya ficheros, adjúntamelo también.