java - charAt(0) 抛出字符串越界异常

标签 java

所以我的老师希望我编写一个程序,我必须读取 txt 文件并将每一行作为字符串按字母顺序分配给 TreeMap。我尝试使用 Scanner 读取文件,并尝试使用 charAt(0) 方法获取每行的第一个字母,但每次运行它时,它都会返回一个错误,提示“线程“main”中出现异常” java.lang.StringIndexOutOfBoundsException: String index out of range: 0"因此,如果有人能指出我在程序中犯的错误,我将非常感激。

Here is a picture of the text file that I am trying to read

 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/

相关文章:

javascript - E/Android运行时: FATAL EXCEPTION: main crash when app start

java - CAN 硬件接收缓冲区的掩码生成

java - AOP + Jenkins + Maven 集成

java - 为什么 node.js 加密模块给出的结果与 AES 加密的 Java Cipher 类不同?

java 字节码 - 小于 int 的类型的表示

java - 无法在 OS X Yosemite 上安装 JRE8/JRE7

java - 字符串 [] 值与字符串值 []

java - 如何包含从插件 wget 下载的 jar 作为 Maven 项目中的依赖项

java - Mockito 中的连续通话测试

java - 如何修复hadoop中的 "Illegal partition"错误?