字符串索引超出范围:-2

时间:2014-01-21 07:03:27

标签: java

以下程序出现异常:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -2
    at java.lang.String.substring(String.java:1911)
    at Names.main(Names.java:33)

换行

System.out.println("The character at index 3 in "+middle+" is "+middle.substring(3, 1));

你觉得这行有什么问题吗?

/* Names.java */

import java.io.*;

public class Names {

/** Performs various string operations on the name John Fitzgerald kennedy.
 *     
 * @param arg is not used
 */

    public static void main(String[] args) {
        String first = "john";
        String middle = "Fitzgerald";
        String last = "Kennedy";
        String initials;
        String firstInit, middleInit, lastInit;

        firstInit = first.substring(0, 1);
        middleInit = middle.substring(0,1);
        lastInit = last.substring(0,1);
        initials = firstInit.concat(middleInit);
        initials = initials.concat(lastInit);

        System.out.println();
        System.out.println(first+" "+middle+" "+last+" ");
        System.out.println(initials);
        System.out.println(last+", "+first+" "+middle);
        System.out.println(last+", "+first+" "+middleInit+".");
        System.out.println(first.toUpperCase()+" "+last.toUpperCase());

        System.out.println(first+" equals john is "+first.equals("john"));
        System.out.println(first+" equals john (ignoring case is) "+first.equalsIgnoreCase("john"));
        System.out.println("The character at index 3 in "+middle+" is "+middle.substring(3, 1));
        System.out.println("The index of \"gerald\" within "+middle+" is "+middle.indexOf("gerald"));
        System.out.println("The index of \"gerald\" within "+last+" is "+last.indexOf("gerald"));

        System.out.println();
    }

}

5 个答案:

答案 0 :(得分:3)

这不起作用:

middle.substring(3, 1)

您的结束值不能大于String#substring()的起始值:

  

引发IndexOutOfBoundsException - 如果beginIndex为否定,或endIndex大于此String对象的长度,或 beginIndex大于{{ 1}}

由于您只想要索引3处的字符,请改为使用endIndex

charAt()

或者,使用范围较窄的middle.charAt(3);

substring

答案 1 :(得分:1)

您必须将(开始,结束)参数传递给substring

middle.substring(3, 4) // '4' since you just want one char

请记住,substring()不会返回索引4的字符。

注意: 更简单的方法是使用charAt(index)

middle.charAt(3)

答案 2 :(得分:1)

方法签名是

public String substring(int beginIndex, int endIndex)

因此,如果你想打一个角色,你应该使用

middle.substring(3, 4);

答案 3 :(得分:0)

middle.substring(from index , to index)在使用子字符串middle.substring(3, 1)

时,您在此处做了什么to index greater than from index

研究Java中的字符串操作

答案 4 :(得分:0)

从o this documentation开始,很明显,如果beginIndex为负数,或者endIndex大于此String对象的长度,或者beginIndex大于endIndex,则subString()方法将抛出IndexOutOfBoundsException。