【问题标题】:java.lang.StringIndexOutOfBoundsException: String index out of range: -4 [closed]java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:-4 [关闭]
【发布时间】:2017-07-04 14:36:22
【问题描述】:

我有这个简单的 Java 代码,它给出了以下错误: java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:-4

代码是:

String date = "14000101";
String repayDate = date.substring(0, 4)+"-"+date.substring(5, 2)+"-"+date.substring(6, 2);

字符串的长度为 8,但从第二部分开始时会出现错误。

有什么想法吗?

谢谢!

【问题讨论】:

  • 读取 java.lang.String.substring(int, int) 的 javadoc
  • 根据文档;抛出 IndexOutOfBoundsException - 如果 beginIndex 或 endIndex 为负,如果 endIndex 大于 length(),或者 beginIndex 大于 startIndex
  • 子字符串方法的第二个参数不是长度而是子字符串的结束位置。所以,你想要这样的东西:date.substring(0, 4)+"-"+date.substring(5, 7)+"-"+date.substring(6, 8);
  • 这里真正有趣的问题是:为什么我们对 ArrayIndexOutOfBounds 和 NPE 有这么大的现有问题......但不是这些东西?

标签: java


【解决方案1】:

date.substring(5, 2) 应该是 date.substring(5, 7)date.substring(6, 2) 应该是 date.substring(6, 8)

第二个参数是所需子字符串的最后一个字符之后的字符的索引。

【讨论】:

    【解决方案2】:

    你给出的是负值:

    [API][1] [1]:http://www.w3api.com/wiki/Java:String.substring()

    public String substring(int beginIndex)
    public String substring(int beginIndex, int endIndex)
    

    如果你将 beginIndex 放在比 endIndex 低的位置,则崩溃。

    你应该这样做:

    String repayDate = date.substring(0, 4)+"-"+date.substring(5, 7)+"-"+date.substring(6, 8);
    

    试试吧! 祝你好运。

    【讨论】:

      【解决方案3】:
      substring(int beginIndex, int endIndex) 
      

      在您的代码中,endIndex 小于 beginIndex。检查this

      beginIndex - the beginning index, inclusive.
      endIndex - the ending index, exclusive.
      
      IndexOutOfBoundsException - if the beginIndex is negative, or 
      endIndex is larger than the length of this String object, or 
      beginIndex is larger than endIndex.
      

      【讨论】:

        【解决方案4】:

        java 和 python 有点不同......

        这在doc 中反映是无效的

         substring(5, 2)
        

        第二个整数必须大于第一个

        if (endIndex > value.length) {
              throw new StringIndexOutOfBoundsException(endIndex);
        }
        

        如果您的意思是在第一个参数之后获得 2 个字符,那么请执行类似的操作

        substring(5, 5 + 2);
        

        甚至更好:

        int beginIndex = 5;
        String dateB = date.substring(beginIndex, beginIndex + 2);
        

        【讨论】:

          【解决方案5】:

          阅读 java.lang.String.substring(int, int) 的 javadoc

          String date = "14000101";
              String repayDate = date.substring(0, 4)+"-"+date.substring(4, 6)+"-"+date.substring(6, 8);
              System.out.println(repayDate);
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2012-03-02
            • 1970-01-01
            • 2016-02-25
            • 2018-11-14
            • 1970-01-01
            • 1970-01-01
            • 2014-04-14
            • 1970-01-01
            相关资源
            最近更新 更多