[英]charAt(0) throws a string out of bounds exception
所以我的老師要我編寫程序,在該程序中,我必須通讀txt文件,並將每一行作為字符串分配給按字母順序排列的TreeMap。 我試圖使用Scanner來讀取文件,並且試圖通過使用charAt(0)方法來獲取每一行的第一個字母,但是每次運行它時,它都會返回一條錯誤消息,指出“線程“ main”中的異常” java.lang.StringIndexOutOfBoundsException:字符串索引超出范圍: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);
}
在讀取第一個字符之前進行長度檢查:
if(line.length() > 0) {
char ch1 = line.charAt(0);
int key = (int)ch1;
list.put(key, line);
}
您的文件可能帶有尾隨換行符, Scanner
刪除該換行符,使您留下一個空字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.