java - 字符串索引越界异常 : string index out of range

标签 java

我找不到有关此异常的答案。程序很简单,但是我不知道为什么不正确。

/**
 * Program selects the first word from the sentence "Hello, my dear!" with
 * the String Classes's methods this.indexOf() and this.substring()  
 * 
 *
 * Last modify: 29th October 2015
 */

public class TakeSubstringWanted {

    public static void main(String[] args) {

        String sentence = "Hello, my dear!";
        String reference = "Hello";

        System.out.println("The sentence is: " + sentence);
        System.out.println("You want to take the first word of that sentence");
        System.out.println("Give me a second...");

        int firstReference = sentence.indexOf(reference);
        int firstLength = reference.length();
        System.out.println("The first reference of the searched word is " + firstReference);
        System.out.println("The first word of the sentence " + sentence + " is: " + "\"" + sentence.substring(firstReference, firstLength) + "\"");
        int secondReference = sentence.indexOf("my");
        System.out.println("The second reference of the searched word is " + secondReference);
        int secondLength = "my".length();
        System.out.println(secondLength);
        System.out.println(sentence);
        System.out.println("The second word of the sentence " + sentence + " is: " + "\"" + sentence.substring(secondReference, secondLength) + "\"");
    }

}

最佳答案

你的问题在最后一行:

System.out.println("The second word of the sentence " + sentence + " is: "
             + "\"" + sentence.substring(secondReference, secondLength) + "\"");

因为您的 secondReference = 7secondLength = 2,但是如果您查看 documentation对于子字符串方法:

public String substring(int beginIndex, int endIndex)

Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.

...

Throws: IndexOutOfBoundsException - if beginIndex or endIndex are negative, if endIndex is greater than length(), or if beginIndex is greater than startIndex

意思是,您要求 substring 返回从索引 7 到索引 2 的字符串,这会导致 IndexOutOfBoundsException。您可能想要做的是:

sentence.substring(secondReference, secondReference + secondLength)

关于java - 字符串索引越界异常 : string index out of range,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33409160/

相关文章:

java - JToolbar 上的调整组件大小

java - 当预期值和实际值似乎相等时,为什么Junit 5中的AssertEquals()失败?

java - 将Runtime.exec与命令中的空格一起使用时的“Cannot run program”

java - 找不到适合 Oracle 数据库连接的驱动程序

java - "Cannot cast"子类到父类(super class)

java - 将可绘制对象的 ArrayList 发送到服务(Java、Android)

java - Android 导入重叠

java - 如何在内部类中调用继承类的构造函数

javascript - 甲骨文 MAF : (Signature Capture) Calling a javascript function from Managed Bean

java - 如何将 jar 放入 Maven 存储库中以允许 pom.xml 从 eclipse 识别它们