我该如何解决此"String index out of range error"?



我在我为学校编写的程序中修复此错误很难解决。我粘贴了下面的Java片段,以及运行代码后收到的错误。


Java摘要:

public static void main(String[] args) throws IOException {
     String largeSpace = " ";
     String smallSpace = " ";
     //Printing header row
     System.out.print("Title" + largeSpace.substring("Title".length()));
     System.out.print("ISBN" + smallSpace.substring("ISBN".length()));
     System.out.print("Course" + smallSpace.substring("Course".length()));
     System.out.print("Enrollment" + 
     smallSpace.substring("Enrollment".length()));
     System.out.print("To Order");
     System.out.println();
     BufferedReader bufferedReader = null;

错误我收到的:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String 
index out of range: -4
    at java.lang.String.substring(Unknown Source)
    at A5WilliamCarter.main(A5WilliamCarter.java:102)

以来" title" .length()为5,而largespace只有长度1,而5个超过1,然后它将抛出stringIndexOutofBoundSexception。您是4个字符。

我不完全确定您在做什么,但我认为可能的解决方法是以下内容:

    System.out.print("Title" + largeSpace*("Title".length()));

您正在分配String largeSpace = " ";,然后尝试从Index 5开始获得它的子字符串,而您的4个字符短。

您无法做

largeSpace.substring("Title".length())
smallSpace.substring("ISBN".length())

这是因为largespace和smallspace每个都有长度1,但是您试图从字符4和5开始进行子字符串。这会引起错误。我不确定您要使用此代码做什么,因此我无法提供解决方案。

相关内容

最新更新