2017-04-21 25 views
1

我试图从一个文件中读取文件,这个文件存储在下面的测验中;Java Buffered Reader来映射

将标识符和问题标识符放在第一行,然后是问题标题,接下来是答案标题,最后是选择的答案。

我试图读取该文件,然后保存它使用一个HashMap

16 TF 
Question 
Because an ArrayList is an indexed collection, you can access its elements using a subscript. 
Answer 
False 
True 
Selected 
1 

258 MC 
Question 
Fill in the blank. A Node is generally defined inside another class, making it a(n) ____ class. 
Answer 
Private 
Inner 
Public 
Internal 
Selected 
2 

37 L5 
Question 
How would you rate your programming skills? 
Answer 
Excellent 
Very good 
Good 
Not as good as they should be 
Poor 
Selected 
-1 

我的代码:

Quiz newquiz = new Quiz(); 
    List<String> newArray = new ArrayList<String>(); 
    Map<Integer, String> newquizmap = new HashMap<Integer, String>(); 
    BufferedReader BufferedReader = new BufferedReader(new FileReader('file.txt')); 
    String line = null; 

    while ((line = BR.readLine()) != null) { 
     String nuquiz[] = line.split(" "); 
     BufferedReader.readLine(); 

     newquiz.newquestionid = Integer.parseInt(parts[0]); 



      lines.add(line); 
       newquizmap.put(newquiz.newquestionid, newArray.toString()); 


      line = BufferedReader.readLine(); 

      System.out.println(newquizmap); 
     } 

    } BR.close(); 

我知道这是不对的,我不即使认为它很接近,但我真的很困难,这有人可以给我任何帮助吗?

编辑:

  Quiz newquiz = new Quiz(); 
    List<String> newArray = new ArrayList<String>(); 
    Map<Integer, String> newquizmap = new HashMap<Integer, String>(); 
    BufferedReader BufferedReader = new BufferedReader(new FileReader('file.txt')); 
    String line = null; 

    while ((line = BR.readLine()) != null) { 
     String nuquiz[] = line.split(" "); 
     BufferedReader.readLine(); 

     newquiz.newquestionid = Integer.parseInt(parts[0]); 



      lines.add(line); 
       newquizmap.put(newquiz.newquestionid, newArray.toString()); 


      line = BufferedReader.readLine(); 

      System.out.println(newquizmap); 
     } 

    } BR.close(); 

尝试这个代码,它似乎充满了每一个值每一个地图的关键?

+3

请不要恶意破坏你的帖子。 – Glorfindel

回答

1

一种方法是将java对象用作散列表值。创建一个新的类来包含以下属性(修改,以处理所有的问题用例):

private String questionId; //This will hold question Id - TF  
private String question; //This will hold the Question - Because an ArrayList is an indexed collection, you can access its elements using a subscript. 
    private List<String> choices; //This will hold the choices - Private Inner Public Internal 
    private Integer selectedChoice; //This will hold the answer 

包括参数的构造函数和类中的其他必要方法。

解析文件,遍历内容,创建这个新类的一个对象,并添加hashmap,其中“id”作为键和“pojo对象”作为值。

注:请更正Java代码的几个其他问题(格式,编码就像变量名标准大写,QuestionSet,由于输出开始..等)