所以我的老师希望我编写一个程序,我必须读取 txt 文件并将每一行作为字符串按字母顺序分配给 TreeMap。我尝试使用 Scanner 读取文件,并尝试使用 charAt(0) 方法获取每行的第一个字母,但每次运行它时,它都会返回一个错误,提示“线程“main”中出现异常” java.lang.StringIndexOutOfBoundsException: String index out of range: 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
会将其删除,留下一个空字符串。
关于java - charAt(0) 抛出字符串越界异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45538855/