字符串索引超出绑定exception,字符串索引超出范围
所以,我正在编写一个简单的程序来输入字符串并计算总数。 米 所以,这是我的代码
for(int i=0; i<=n; i++) { if((str.charAt(i)=='m')) { } else { count++; } } System.out.println("The total number of m is "+count);
其中n=str.length();
和str是我已经采取的一个字符串,但是这个错误不断出现
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 14 at java.lang.String.charAt(String.java:646) at javaapplication.JavaApplication.main(JavaApplication.java:28 Java Result: 1
什么是这个错误以及如何删除它?
length() == n
字符串具有从0到n-1的有效索引;
更改
for(int i=0; i<=n; i++)
至
for(int i=0; i
记住字符串从0索引到StringName.length() – 1.因为你正在迭代StringName()。length – 你实际上正好在字符串的“边界”之外,这导致了错误。 你需要确保你的索引在你的for循环中是正确的。
String变量中的字符从0索引开始。
此外,如果要计算小写字母m
的总外观,请将count++
移至if block statement
。
n=str.length() - 1; for(int i=0; i<=n; i++) { if((str.charAt(i)=='m')) { count++; } } System.out.println("The total number of m is "+count);
想象一下,你有以下7长度数组:
----------------------------- | 0 | 1 | 2 | 3 | 4 | 5 | 6 | <-- Array index ----------------------------- |10 |20 |30 |40 |50 |60 |70 | <-- Array values -----------------------------
在这种情况下,for循环for(int i=0; i<=n; i++)
将循环8次,从索引0到7迭代。
但是索引7处的数组元素不存在,因此给出outOfBoundsException
。
for for for循环for(int i=0; i
charat与索引一起工作(从n到1工作),但在你的for中你得到的条件是你有i = n,在这种情况下charat抛出exception,因为它没有数组中的索引