2017-08-07 33 views
0

因此,我的老師希望我編寫的程序必須通過txt文件讀取,並按照字母順序將每行作爲字符串分配給TreeMap。我試圖用掃描儀來讀取文件,我試圖通過使用charAt(0)方法獲得每行的第一個字母,但每次運行它時,它都會返回一個錯誤,說「線程中的異常」main「 java.lang.StringIndexOutOfBoundsException:字符串索引超出範圍:0「所以如果任何人都可以指出我在程序中犯的錯誤,我會非常感激。charAt(0)拋出一個字符串越界異常

Here is a picture of the text file that I am trying to read

TreeMap<Integer, String> list= new TreeMap<Integer, String>(); 
    Scanner scan= new Scanner(System.in); 
    System.out.println("Enter file name"); 
    String filename= scan.nextLine(); 

    try{ 
    scan= new Scanner (Paths.get(filename)); 
    } 
    catch (IOException ioException) 
    { 
    System.err.println("Error opening file. Terminating."); 
    System.exit(1); 
    } 

    try 
    { 
    while(scan.hasNextLine()) 
    { 
    String line= scan.nextLine(); 
    char ch1 = line.charAt(0); 
    int key=(int) ch1; 
    list.put(key, line); 
    } 
    } 
catch (IllegalStateException stateException) 
{ 
    System.err.println("Error reading from file. Terminating."); 
    System.exit(1); 
} 
+6

這意味着您試圖獲取第一個字符的字符串爲空。在嘗試獲取角色之前,您需要檢查它。 – Carcigenicate

+1

您的文件中有一個換行符。 –

+1

輸入數據中有空行。 – Thilo

回答

1

讀取第一個字符之前做一個長度檢查:

if(line.length() > 0) { 
    char ch1 = line.charAt(0); 
    int key = (int)ch1; 
    list.put(key, line); 
} 

您的文件可能有一個換行符,這Scanner剝掉,讓你有一個空字符串。

+0

實際上可能是有一個尾隨的換行符。 –

+0

@MadPhysicist非常感謝。 –