StringIndexOutOfBounds在Java中 [英] StringIndexOutOfBounds in Java

查看:194
本文介绍了StringIndexOutOfBounds在Java中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里有两个完全的代码副本,除了在for循环中有'<',而另一个有'< ='。有人可以解释为什么当我使用'< =',但是它工作正常与'<'

I have two exact copies of code here, except one has '<' in the for loops while the other has '<='. Could someone please explain why I get the index out of bounds exception when I use '<=', but then it works fine with '<'

错误代码:

for(int i = 0; i <= str.length(); i++) {
      int count = 0;
      char currentChar = str.charAt(i);
      for(int j = 0; j <= str.length(); j++) {
        if (currentChar == str.charAt(j) ) {
          count++;



工作代码:


Working code:

for(int i = 0; i < str.length(); i++) {
      int count = 0;
      char currentChar = str.charAt(i);
      for(int j = 0; j < str.length(); j++) {
        if (currentChar == str.charAt(j) ) {
          count++;



如果我不使用< =字符串中的最后一个字符?


If I don't use <= how will it compare the last character in the string?

推荐答案

有效的 String 就像任何数组中的索引一样,从零到长度减一。所以,如果你设置你的条件到 i< = str.length(),你将得到字符串之外。

Valid String indexes in Java, just like the indexes in any array, go from zero to length minus one. So clearly if you set up your condition to go up to i <= str.length(), you'll get outside the string.

请记住,内部的 String 只不过是一个 char [] 再次:有效索引从 0 length-1 。这是一个约定,其次是许多其他编程语言,决定从零开始计数,而不是一个。

Remember that a String on the inside is nothing more than a char[], and again: the valid indexes go from 0 to length-1. This is a convention, followed by many other programming languages that decided to start counting from zero instead of one.

这篇关于StringIndexOutOfBounds在Java中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆