2017-04-21 48 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,由於輸出開始..等)