2013-04-22 74 views
1

當我編譯和運行我的測試中,出現 此消息: StringIndexOutOfBoundsException: String index out of range: -3的StringIndexOutOfBoundsException:字符串索引超出範圍:-3

我覺得我已經做了一些錯誤的子串,但我可以」弄清楚在哪裏。

這應進行測試:

Argument for parsePathname: .mp3 
Output getAuthor: empty String 
Output getTitle: empty String 

這是我的代碼:

public void parseFilename(String filename) 
{ 
    //Dateiendung entfernen 
    int ending; 
    ending = filename.lastIndexOf('.'); 
    filename = filename.substring(0,ending); 
    filetype = filename.substring(filename.length()-3); 


    //Abfrage, ob Bindestrich(hyphen) vorhanden 
    //i+1 ist Position vom Bindestrich 
    boolean has_hyphen = false; 
    int i; 


    for(i=0; i<filename.length(); i++) 
    { 
     if(filename.charAt(i) == ' ' && filename.charAt(i+1) == '-' && filename.charAt(i+2) == ' ') 
     { 
      has_hyphen = true; 
      break; 
     } 
    } 

    if (!has_hyphen || (filename.length() == 1 && filename.charAt(0) == '-')) 
    { 
     author =""; 
     title = filename; 
    } 


    if (filename.length() == 0 || (filename.charAt(0) == ' ' && filename.charAt(1) == '-' && filename.charAt(2) == ' ')) 
    { 
     author = ""; 
     title = ""; 
    } 

    if (has_hyphen) 
    { 
     author = filename.substring(0,i); 
     author = author.trim(); 
     title = filename.substring(i+2); 
     title = title.trim(); 
    } 
} 

回答

0

我的猜測是,你的例外發生在這裏:

ending = filename.lastIndexOf('.'); 
filename = filename.substring(0,ending); 
filetype = filename.substring(filename.length()-3); //<- Here 

如果.是第一字符的文件名(如".mp3"),索引將爲0並且子字符串之後將是大小爲0的字符串。 然後,您使用-3調用substring,並拋出IndexOutOfBoundsException。確保字符串不僅包含文件類型。

如果您知道輸入參數,它總是會包含一個文件擴展名,你可以阻止這樣的:

ending = filename.lastIndexOf('.'); 
if(ending == 0) { 
    filetype = filename; 
    filename = ""; 
} else { 
    ... 

你應該得到filetype你刪除它獲得的文件名之前。在此行之後:

filename = filename.substring(0,ending); 

filename不再包含文件擴展名。

+0

非常感謝,它現在可以工作,我明白爲什麼! :) – theblackcrow1 2013-04-22 15:02:36

相關問題