因此,我的老师要我编写程序,在该程序中,我必须通读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);
}


您的文件可能带有尾随的换行符,该会剥离,留下空字符串。

10-07 19:22
查看更多