2012-12-03 64 views
0

好了,這裏是什麼,我必須寫一個解釋:從文本文件中讀取作爲ArrayList/HashMap的

  • getBreadInfo - 讀bread.txt到一個數組列表(含麪包 名,$和價格),然後分配到數組breadInfo [],然後 返回此數組SandwichApp顯示麪包菜單。
  • getBread - 類似於getBreadInfo,只是它僅包含 麪包名稱,並返回另一個陣列麪包[]爲SandwichApp推測其麪包用戶選擇,因爲用戶輸入一個號碼 關聯與麪包 出(索引+1),而不是麪包名稱。
  • getMapBreadPrice - 類似於上面的兩個,除了它返回包含麪包名稱(鍵)和價格(價值) 爲SandwichApp找出什麼是用於選擇的麪包用戶 價格對值的 哈希映射。

這是我寫的。只是想知道這是否正確?

public class SandwichDB { 
private ArrayList<String> breadsList = null; 

public String[] getBreadInfo() 
{ 
    breadsList = new ArrayList<>(); 

     try (BufferedReader in = 
       new BufferedReader(
       new FileReader("bread.txt"))) 
     { 
      String line = in.readLine(); 
      while (line != null) 
      { 
       String[] elems = line.split("~"); 
       breadsList.add(elems[0]+ " $" + elems[1]); 
      } 

     } 
     catch(IOException e) 
     { 
      System.out.println(e); 
      return null; 
     } 
    String[] breadInfo = breadsList.toArray(new String[]{}); 
    return breadInfo; 
} 
public String[] getBread() 
{ 
    breadsList = new ArrayList<>(); 

     try (BufferedReader in = 
       new BufferedReader(
       new FileReader("bread.txt"))) 
     { 
      String line = in.readLine(); 
      while (line != null) 
      { 
       String[] elems = line.split("~"); 
       breadsList.add(elems[0]); 
      } 

     } 
     catch(IOException e) 
     { 
      System.out.println(e); 
      return null; 
     } 
     String[] bread = breadsList.toArray(new String[]{}); 
     return bread; 
} 
public HashMap<String, String> getMapBreadPrice() 
     { 
      HashMap<String, String> mapBreadPrice = new HashMap<>(); 
      String line, elems[]; 
      try 
      { 
       FileReader fr = new FileReader("bread.txt"); 
       BufferedReader br = new BufferedReader(fr); 

       while ((line=br.readLine()) != null) 
       { 
        elems = line.split("~"); 
        mapBreadPrice.put(elems[0], elems[1]); 
       } 
      } 
      catch(IOException e) 
      { 
       System.out.println(e); 
       return null; 
      } 
      return mapBreadPrice; 
     } 
     } 
+3

它做你所期望的嗎? – assylias

回答

0

第一readLine看臺while,因此前不再重複。因此,時間不會結束。

for (;;) { 
    String line = in.readLine(); 
    if (line == null) { 
     break; 
    } 
0

看起來你似乎正在閱讀相同的文件3次,以建立3個結構。您應該通過讀取文件來構建數據結構。