我不明白为什么我得到索引超出约束的异常?

时间:2013-11-12 15:07:38

标签: java indexoutofboundsexception

这是前一年有错误的考试题,但我似乎无法理解为什么?我一直在收到这个错误:

  

线程“main”中的异常java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:21

public class SwimmingPool{ 

  public static void countSpaces(String s){
    int count = 0;

    for(int i = 0; i <= s.length(); i++){
      if(s.charAt(i) == ' '){
        count++;
      }
    }
    System.out.println("Percent of spaces is" + count /
    s.length());
  }

  public static void main (String[] args){

    String s = "lefhg aljdfgh liauh h";
    countSpaces(s);
  }      
}

5 个答案:

答案 0 :(得分:4)

for(int i = 0; i <= s.length(); i++){

应该是(观察它只是小于符号,不小于等于):

for(int i = 0; i < s.length(); i++){

编辑:

String索引从ZERO开始,然后升至String length() -1。如果你使用<=s.length(),你会看到超过字符串结尾的一个索引(当=条件检查发生时)。

答案 1 :(得分:1)

你的问题在这里:

for(int i = 0; i <= s.length(); i++)

应该是:

for(int i = 0; i < s.length(); i++) //note that it is LESS THAN 

字符串索引在Java中从0开始,从0运行到string.length() - 1。因此,您尝试访问位置string.length()中不存在的字符。这就是你获得例外的原因。

答案 2 :(得分:0)

String内部使用数组,数组索引的有效范围是0length-1for循环中的代码将尝试访问array[length]元素,该元素将抛出ArrayIndexOutOfBoundException

因此,将for循环条件更改为仅迭代到length-1索引(最后一个元素)。

for(int i = 0; i <= s.length(); i++)

应该是

for(int i = 0; i < s.length(); i++)

答案 3 :(得分:0)

您需要进行以下2项更改:

1    改变

 for(int i = 0; i <= s.length(); i++){

 for(int i = 0; i < s.length(); i++){

2 count / s.length()需要更改。如果你这样做,你的例子就会为零。

改为使用100.0 *count / s.length(),例如

System.out.printf("Percent of spaces is " + 100.0 *count / s.length());

控制台输出:

Percent of spaces is 14.285714285714286

答案 4 :(得分:0)

首先,我们可以访问“s.length-1”而不是“s.length”,因为我们得到了异常。 其次,以“count /s.length()”来获得百分比将是困难的,因为它们都是int数据类型,并且结果是十进制的,它将四舍五入并显示为0.如果我们将count指定为加倍,然后我们就可以得到确切的百分比。

public static void countSpaces(String s){         double count = 0.0;

    for(int i = 0; i < s.length(); i++){
      if(s.charAt(i) == ' '){
        count++;
      }
    }
    System.out.println("Percent of spaces is" + count /
    s.length());
  }

  public static void main (String[] args){

    String s = "lefhg aljdfgh liauh h";
    countSpaces(s);
  }
相关问题