java StringIndexOutOfBounds使用String.substring()时的异常

时间:2012-12-11 20:50:48

标签: java

如何通过Java中的“StringIndexOutOfBounds”异常获取?以下是该程序的一些示例代码。

Scanner diskScanner = new Scanner (new File("C:\\Program Files\\SProjects\\temp\\test.ssc")); // opens file to read

line = diskScanner.nextLine();

if (line.substring(0,5).equals("PRINT")) {  // Line 42
    System.out.println(line.substring(8));
}

它似乎来自“42”行或line.substring(),有人能告诉我为什么会抛出这个异常吗?

4 个答案:

答案 0 :(得分:5)

这意味着您正在尝试访问字符串结尾之后的字符。如果String只有4个字符长,尝试从索引0 - 8获取子字符串将抛出此异常。

您可以检查字符串的长度,以确保它足够长:

line = diskScanner.nextLine(); // Scans files
//This condition with short circuit and skip the second condition if it is too short,
//so no exception will be thrown.
if (line.length() > 8 && line.substring(0,5).equals("PRINT")) { // Print function
    System.out.println(line.substring(8));
}

或者,您可以捕获并处理异常:

line = diskScanner.nextLine(); // Scans files
try {
if (line.substring(0,5).equals("PRINT")) { // Print function
    System.out.println(line.substring(8));
}
} catch (IndexOutOfBoundsException e) {
    //Do Something...
}

答案 1 :(得分:1)

引用documentation

    如果substring(beginIndex)为负数或大于此IndexOutOfBoundsException对象的长度,则
  • beginIndex会引发String

  • 如果substring(beginIndex, endInded)为否定,或IndexOutOfBoundsException大于此beginIndex对象的长度,则{li>

    endIndex会引发String,或{{} 1}}大于beginIndex

答案 2 :(得分:1)

首先是StringIndexOutOfBoundException,而不是 StringOutOfrange

来自API:

  

按String方法抛出,以指示索引为负数   或大于字符串的大小。对于某些方法,如   charAt方法,当索引相等时也抛出此异常   到字符串的大小。

示例:

String line="abc";
System.out.println(line.subString(4));

the above code would throw **StirngIndexOutOfBoundException** as its trying to access index 4 which doesn't exits.

答案 3 :(得分:0)

字符串对象line的长度小于6.当您运行调试器时,line的值是多少?我的猜测是它是空字符串或只是行终止符。或者,当ARS指出并且您的字符串不符合您要求的if长度时,它会超过8块。回想一下,基于Java的索引为零,因此您的字符串的长度可能小于9