2017-02-02 103 views
-2

此錯誤很難調試。它也不是經常發生。有人可以幫忙嗎? substring方法是否可能被破壞?StringIndexOutOfBoundsException:字符串索引超出範圍32 in循環

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 32 
     at java.lang.String.substring(String.java:1765) 
     at mmk.basej.main(basej.java:186) 

Error in line: "tmp1 = filePathShort1.substring(0, 10)" 

這是我的代碼:

  String tmp = null;    
      String pdf_name = null; 
      for (int z = 0; z < list_chek.length; z++) {     
       if (list_chek[z].toString().indexOf("pdf") > 0 | list_chek[z].toString().indexOf("tif") > 0 | list_chek[z].toString().indexOf("jpg") > 0) { 
        String filePath1 = new String(); 
        String filePathShort1 = new String(); 
        String tmp1 = null; 
        filePath1 = dir + list_chek[z].toString(); 
        filePathShort1 = list_chek[z].toString(); 
        tmp1 = filePathShort1.substring(0, 10) 
          + filePathShort1.substring(20, filePathShort.indexOf("tsd7")-1) 
          + "_" 
          + filePath1.substring(
            filePath1.indexOf("tsd7"), filePath1 
              .length() - 4); 

        if (name_no_time.equals(tmp1)) { 
         //System.out.println(name_no_time+" ---- "+tmp1); 
         System.out.println("PDF_NAME " + list_chek[z].toString()); 
         pdf_name = list_chek[z].toString(); 
        } 
        else if ((list_chek[z].toString().indexOf("jpg") > 0) && ((name_no_time + "_1").equals(tmp1))) { 
         System.out.println("JPG_NAME " + list_chek[z].toString()); 
         pdf_name = list_chek[z].toString(); 
        }    
       } 
      } 
+2

StringIndexOutOfBounds非常明瞭。 – khelwood

+0

另外,我認爲'tmp1 = filePathShort1.substring(0,10)'是不可能的,因爲[Java API文檔StringIndexOutOfBoundsException](https://docs.oracle.com/javase/7/ docs/api/java/lang/StringIndexOutOfBoundsException.html)_Thrown由String方法指示索引是否定的或大於字符串的大小。對於某些方法(如charAt方法),當索引等於string._的大小時,也會引發此異常。您的錯誤很可能是由於代碼中的另一行。 –

+0

這是關於tmp1計算的東西。 tmp1 = 2017-02-02005002801AFAC_tsd7 and filePathShort1 = 2017-02-02_15-32-46_005002801AFAC_tsd7.pdf – antbug

回答

0
filePathShort1 = list_chek[z].toString(); 
tmp1 = filePathShort1.substring(0, 10) 

如果list_chek [Z]的ToString具有長度< 10,然後substring(0, 10)比所提供的字符串長。這是您的索引越界來自的地方。它試圖引用和超出tmp1的界限。 如果list_chek [z] < 20.你會在下一行中得到同樣的問題20.你需要在調用子串之前檢查你的字符串長度。

+0

因此,如果'filePathShort1 = 2017-02-02_15-32-46_005002801AFAC_tsd7.pdf'和tmp1必須如下:'2017-02- 02005002801AFAC_tsd7'我必須使用'tmp1 = filePathShort1.substring(0,9)'而不是? – antbug

+0

字符串有固定的大小:'filePathShort1 = 2017-02-02_15-32-46_005002801AFAC_tsd7.pdf'和'tmp1 = 2017-02-02005002801AFAC_tsd7' – antbug

+0

你確定它們的長度和長度都一樣嗎?你可能想要插入一個調試語句來檢查。事實上,它有時而不是其他的,並且在那條線上因爲這個例外而失敗,這是一個強有力的指標,說明它們不夠長。 – WillD

相關問題