简体   繁体   中英

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. 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.

这是我尝试阅读的文本文件的图片

 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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