有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

indexoutofboundsexception Java未按预期获得“StringIndexOutOfBoundsException”

我有以下代码

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 在爪哇。朗,弦。charAt(String.java:658) 在测试中。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'
  • 它不应该作为第一个程序编译失败吗
  • 我错过了什么

共 (3) 个答案

  1. # 1 楼答案

      //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 
    
  2. # 2 楼答案

    由于str"x",所以else if甚至没有运行

    if条件

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

    true,因为str.indexOf('x')返回0,而indexes也是0{}

    因此,is被设置为false,并且else if条件永远不会被计算。因此,没有IndexOutOfBoundsException发生

  3. # 3 楼答案

    因为您的一个字符串通过了第一个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没有被评估