2014-03-07 94 views
-3

我有一個簡單的程序讀取文件。現在線路之間有一個空白區域。我得到StringIndexOutOfBoundsException:String索引超出範圍:0錯誤。請幫助StringIndexOutOfBoundsException:字符串索引超出範圍:0讀取文件時

class main{ 
    public static void main(String args[]) { 
     String str; 
     try { 
    BufferedReader br = new BufferedReader (new FileReader("train.txt")); 
    while((str=br.readLine())!=null){ 
    System.out.println(str); 
    int a=str.charAt(0); 

    if(str.trim().length()==0){ 
     System.out.println("stupid"); 
    } 
    else if(a==32){ 
     System.out.println("ddddd"); 
    } 

    else if(str.charAt(0)=='A' ||str.charAt(0)=='a'){ 
     System.out.println("hahha"); 
    } 
    else if(str.charAt(0)=='C' ||str.charAt(0)=='c'){ 
     System.out.println("lol"); 
    } 

    else if(str.charAt(0)=='D' ||str.charAt(0)=='d'){ 
     System.out.println("rofl"); 
    } 
    else{ 
    System.out.println("blank"); 
    } 


} 
     } 
catch (FileNotFoundException e){ 
    System.out.println(e); 
} 
catch (IOException e){ 
    System.out.println(e); 
} 
    } 
+0

到達2014年3月21日10:30 38472特快 取消40003 這是我的文件中包含的數據。我的代碼無法通過到達和取消行之間的空格 – Sidarth

+1

使用堆棧跟蹤發佈您的異常。 –

回答

3

如果一行爲空,則索引0處沒有字符,因爲字符串爲空。您正在執行此行:

int a=str.charAt(0); 

測試之前是否爲空白。有幾種可能的解決方案。一是重組這樣的代碼:

if(str.trim().length()==0){ 
    System.out.println("stupid"); 
    continue; // so rest of loop body is skipped 
} 
int a=str.charAt(0); 
if(a==32){ 
    System.out.println("ddddd"); 
} 
+0

我一直是一個傻瓜... – Sidarth

+0

感謝大開眼界 – Sidarth

0

該線下方將拋出一個StringIndexOutOfBoundsException當讀取一個空行。

int a=str.charAt(0); 

將其替換爲:

if(str.trim().length()>0) 
a=str.charAt(0); 
+1

解釋爲什麼這是通過編輯答案。 –

+0

你是指什麼編輯? –

+0

_總是使用大括號。有關如果不這樣做會發生什麼的示例,請看下面這個問題:http://stackoverflow.com/questions/22177675/else-statement-is-a-syntax-error –

相關問題