[英]String index out of bounds? Where?
This is my code for finding the no. 这是我找不到的代码。 of vowels in a string:
字符串中的元音:
{
String inyo=inpeo.getText().toLowerCase();
System.out.println(inyo); // Just checking for an empty string
int vowcount=0;
for(int i=0;i<=inyo.length();i++)
{
char rol=inyo.charAt(i);
if(rol=='o'||'u'==rol||rol=='a'||rol=='e'||rol=='i')
{
vowcount=vowcount+1;
System.out.println(vowcount);
}
numout.setText(""+vowcount);
}
}
Now, nothing is wrong with the output here-it finds the exact no. 现在,这里的输出没有任何问题 - 它找到了确切的数字。 of vowels as I intended.
我想要的元音 But it gives me this error:
但它给了我这个错误:
Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range: 5
at java.lang.String.charAt(String.java:646)
at WordCheck.jButton2ActionPerformed(WordCheck.java:147)
// Extra errors removed as they're irrelevant to my issue
As a result, there is no way of reusing the program other than closing and restarting it. 因此,除了关闭和重新启动程序之外,无法重新使用该程序。 when the output is coming out as desired, why am I getting this error?
当输出按需要出现时,为什么我会收到此错误? I don't get any empty Strings, either.
我也没有得到任何空的弦乐。
The last iteration of the for
loop is causing the exception (when i == inyo.length()
). for
循环的最后一次迭代导致异常(当i == inyo.length()
)。 Simply replace it with: 只需将其替换为:
for(int i=0; i<inyo.length(); i++)
i<=inyo.length()
here. i<=inyo.length()
这里。 The String index starts from 0. The length count starts from one. String索引从0开始。长度计数从1开始。 So, the last index of a String is 4 when its length is 5.
因此,当String的长度为5时,String的最后一个索引是4。
It should be 它应该是
i<inyo.length()
Your for
loop is going one too far, this 你的
for
循环太过分了,这个
for(int i=0;i<=inyo.length();i++)
should be 应该
for(int i=0;i<inyo.length();i++)
Note that when i == invo.length()
it's passed the end of the array, because Java starts indexing with 0
. 请注意,当
i == invo.length()
它会传递数组的末尾,因为Java开始使用0
索引。
The for loop should be for循环应该是
for(int i=0; i<inyo.length(); i++)
Presently when it goes to the last iteration the index of the string is 4 whereas inyo.length()
is 5. Hence it results in out of bounds. 目前,当它进入最后一次迭代时,字符串的索引是4而而
inyo.length()
是5.因此它导致超出范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.