【问题标题】:What is causing this StringIndexOutOfBoundsException?是什么导致了这个 StringIndexOutOfBoundsException?
【发布时间】:2019-07-01 01:53:20
【问题描述】:

我正在编写一个程序,该程序从文本文件中获取姓名并打印姓名的首字母。

名字在“Last,First M”中。格式,每个名称位于单独的一行。

因为文本文件包含我班上每个人的名字,所以我不包括在这篇文章中。

我收到的错误是: 线程“主”java.lang.StringIndexOutOfBoundsException 中的异常:字符串索引超出范围:1 在 java.lang.String.substring(String.java:1963) 在 AS01a.main(AS01a.java:28)

/* My Name
** February 6, 2019
** Class Name
** Assignment Name
** Collaborations: None
*/
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class AS01a{
   public static void main(String args[]) throws FileNotFoundException{
      String DEFAULT_FILE_NAME = "AS01.txt";
      String fileName;
      if (args.length != 0)  
         { fileName = args[0]; }
      else
         { fileName = DEFAULT_FILE_NAME; }

      Scanner input = new Scanner(new File(fileName));
      String fullName, first, middle, last, initials;

      while(input.hasNextLine()){

         fullName = input.nextLine();

         //Dividing the full name into individual initials
         first = fullName.substring(fullName.indexOf(" ")+1, fullName.indexOf(" ")+2);
         middle = fullName.substring(fullName.lastIndexOf(" ")+1, fullName.lastIndexOf(" ")+2);
         last = fullName.substring(0,1);

         //Testing to see if the full name contains a middle name
         if(fullName.indexOf(" ") == fullName.lastIndexOf(" ")){
            initials = first + ". " + last + ".";
         }

         else{
            initials = first + ". " + middle + ". " + last + ".";
         }

         if(input.hasNextLine()){
            System.out.println(fullName + " yields " + initials);
         }  
      }
   }
}

我的结果符合预期,唯一的问题是前面提到的错误。

【问题讨论】:

  • 其中一行格式错误。你试过调试吗?

标签: java


【解决方案1】:

fullName 似乎是一个空字符串,您可以使用调试器轻松检查。它为空的原因是您的文件中可能有一个空行。如果是这样,您应该添加像 if (fullName.isEmpty()) continue; 这样的空检查来遍历剩余的行。

【讨论】:

    【解决方案2】:

    您的 StringIndexOutOfBoundsException 可能是由于您收到的数据,因为我们不知道“全名”。如果某人没有名字/中间名/姓氏,您将收到异常,因为您在初始化第一个中间名和最后一个之前没有检查这个。将初始化程序移到 if 语句中,看看是否有帮助。
    试试这个。

    while(input.hasNextLine()){
       fullName = input.nextLine();
       if(fullName.isEmpty())
                 fullName = input.nextLine();
       //Testing to see if the full name contains a middle name
       if(fullName.indexOf(" ") == fullName.lastIndexOf(" ")){
          first = fullName.substring(fullName.indexOf(" ")+1, fullName.indexOf(" ")+2);
          last = fullName.substring(0,1);
          initials = first + ". " + last + ".";
       }
       else{
          first = fullName.substring(fullName.indexOf(" ")+1, fullName.indexOf(" ")+2);
          middle = fullName.substring(fullName.lastIndexOf(" ")+1, fullName.lastIndexOf(" ")+2);
          last = fullName.substring(0,1);
          initials = first + ". " + middle + ". " + last + ".";
       }
       if(input.hasNextLine()){
          System.out.println(fullName + " yields " + initials);
       }  
    }
    

    【讨论】: