2015-10-01 129 views
0

我使用arraylist來存儲數據,我嘗試沒有任何if語句的程序從文件讀取並填充arraylis並打印它,它工作正常,但是當我使用迭代,如果語句和邏輯條件下,它給出的異常超出範圍的ArrayList中,arraylist超出範圍

ArrayList<String> accon = new ArrayList<String>(); 
     ArrayList<Double> balance = new ArrayList<Double>(); 
     try { 
      BufferedReader Buffer = new BufferedReader(new FileReader(new File(
        "D://transactions.txt"))); 
      String line = null; 
      while ((line = Buffer.readLine()) != null) { 
       // String arr[] = line.split(" "); 
       String accn = line.substring(0, 17); 
       String Case = line.substring(18, 19); 

       double a = Double.parseDouble(line.substring(20)); 
       // System.out.print(balance.size()); 
       // for (int i = 0; i < accon.size(); i++) { 
       int i = 0; 
       System.out.print(accon.get(i).equals(accn)); 
       while (accon.size() >= i) { 

        if (accon.get(i).equals(accn)) { 

         if (Case.equals("D")) { 
          balance.set(i, balance.get(i) - a); 

         } else { 
          balance.set(i, balance.get(i) + a); 

         } 
        } else { 
         accon.add(accn); 
         balance.add(a); 

         // break; 
        } 
        i++; 
       } 

       // } 

      } 
      System.out.print("-------------------"); 
      for (int i = 0; i < accon.size(); i++) { 
       System.out.println(accon.get(i)); 
       System.out.println(balance.get(i)); 
       // System.out.println(accon.size()); 

      } 

     } catch (Exception e) { 
      System.out.print("" + e); 
     } 

java.lang.IndexOutOfBoundsException:指數:0,大小:0

+0

accon是空的,您可能期望什麼其他行爲? – redFIVE

+0

請幫助我們指出 –

+0

上發生錯誤的代碼行請格式化您的代碼,移除您的測試評論行並指定發生異常的位置。 –

回答

3

您不必在列表中accon任何元素,但您在使用accon.get(0)

System.out.print(accon.get(i).equals(accn)); //here is the error 

導致錯誤說你正在閱讀的0指數,但名單大小0

2

accon變量無關,當你試圖從它那裏得到的東西,在這裏:

System.out.print(accon.get(i).equals(accn)); 

這裏:

if (accon.get(i).equals(accn)) { 

考慮到你的對象,錯誤在打印命令中,並且你的迭代在內因此:將永遠不會被處理:while (accon.size() >= i) {

您必須先將對象添加到它,以便您可以迭代和刪除的對象,所以你可以走出while