【问题标题】:Java - not getting "StringIndexOutOfBoundsException" when expectedJava - 在预期时没有得到“StringIndexOutOfBoundsException”
【发布时间】:2014-09-12 22:07:18
【问题描述】:

我有以下代码

public class test{
    public static void main(String[] args){
        String one = "x";
        if(one.charAt(one.indexOf('x')+1)== 'p'){
            System.out.println("test");
        }
    }
}

这会导致以下错误:

线程“main”中的异常 java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:1 在 java.lang.String.charAt(String.java:658) 在 test.main(test.java:4)

我预计会发生这种情况,我的理解是它的发生是因为字符串只有 1 个索引 (0),因此无法在索引 1 处找到字符

one.charAt(one.indexOf('x')+1)== 'p'

如果我的理解是正确的,我无法理解为什么这个其他程序没有同样的问题

class XClass{
   boolean doubleX(String str){
      boolean is = false;
      int indexes = str.length()-1;
      if(str.indexOf('x')== indexes){
         is = false;
      }else if(str.charAt(str.indexOf('x')+1)=='x'){//same code as the program above
         is = true;
      }
      return is;
   }
}

public class ImplementXClass{
   public static void main(String[] args){
      XClass Xmen = new XClass();
      boolean result = Xmen.doubleX("x");
      System.out.println(result);
   }
}

即使方法参数是一个带有一个索引(“x”)的字符串,这个程序也能成功编译。

  • 如果没有索引 1,程序如何运行 str.charAt(str.indexOf('x')+1)=='x' 这一行。
  • 不应该作为第一个程序编译失败吗?
  • 我错过了什么?

【问题讨论】:

  • 因为该代码永远不会被执行。并且第一个程序没有编译错误。

标签: java indexoutofboundsexception


【解决方案1】:

str"x"else if 甚至没有运行。

if 条件

if(str.indexOf('x') == indexes)

true,因为str.indexOf('x')返回0,而indexes也是0——str.length() - 1

因此,is 设置为 false 并且永远不会评估 else if 条件。因此,不会出现IndexOutOfBoundsException

【讨论】:

    【解决方案2】:

    因为你的一个字符串通过了第一个if 条件,

    int indexes = str.length()-1; // length is 1, 1-1 is 0.
    if(str.indexOf('x')== indexes){ // str.indexOf('x') == 0
      is = false; // <-- hits this.
    

    您的else if 未被评估。

    【讨论】:

      【解决方案3】:
        //str = "x"
        int indexes = str.length()-1; //indexes = 0;
        if(str.indexOf('x')== indexes){  //evals to true, because the index of x is 0 in string "x"
           is = false;
        } else { 
           //... never executes because above evaluated to true 
      

      【讨论】:

        猜你喜欢
        • 2017-01-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-15
        • 1970-01-01
        • 2019-09-16
        相关资源
        最近更新 更多