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

Gal*_*are 0 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));
}
Run Code Online (Sandbox Code Playgroud)

它似乎来自"42"行或line.substring(),有人可以告诉我为什么抛出这个异常?

fem*_*gon 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));
}
Run Code Online (Sandbox Code Playgroud)

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

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...
}
Run Code Online (Sandbox Code Playgroud)