因此,我的老師希望我編寫的程序必須通過txt文件讀取,並按照字母順序將每行作爲字符串分配給TreeMap。我試圖用掃描儀來讀取文件,我試圖通過使用charAt(0)方法獲得每行的第一個字母,但每次運行它時,它都會返回一個錯誤,說「線程中的異常」main「 java.lang.StringIndexOutOfBoundsException:字符串索引超出範圍:0「所以如果任何人都可以指出我在程序中犯的錯誤,我會非常感激。charAt(0)拋出一個字符串越界異常
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);
}
這意味着您試圖獲取第一個字符的字符串爲空。在嘗試獲取角色之前,您需要檢查它。 – Carcigenicate
您的文件中有一個換行符。 –
輸入數據中有空行。 – Thilo