简体   繁体   English

charAt(0)抛出字符串超出范围的异常

[英]charAt(0) throws a string out of bounds exception

So my teacher wants me to write program where I have to read through a txt file and assign each line as a string to a TreeMap in alphabetic order. 所以我的老师要我编写程序,在该程序中,我必须通读txt文件,并将每一行作为字符串分配给按字母顺序排列的TreeMap。 I tried to use Scanner to read through the file and I'm trying to get the first letter of each line by using the charAt(0) method but every time I run it, it returns an error saying "Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0" So if anyone can point out the mistakes I made in the program I would really appreciate it. 我试图使用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);
 }

Make a length check before reading the 1st character: 在读取第一个字符之前进行长度检查:

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

Your file likely has a trailing newline, which Scanner strips off, leaving you with an empty string. 您的文件可能带有尾随换行符, Scanner删除该换行符,使您留下一个空字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM