java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:10 ---.length() 循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20660463/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java.lang.StringIndexOutOfBoundsException: String index out of range: 10 ---.length() loop
提问by judge
Hello guys here is my code
大家好,这是我的代码
for (int i = 0; i <= alignedSeqA.length(); i++) {
if(alignedSeqA.charAt(i)==alignedSeqB.charAt(i)) {
alignedSeqPenalty +="0";
}
else if(alignedSeqA.charAt(i)=='-'){
alignedSeqPenalty +="2";
}else if(alignedSeqB.charAt(i)=='-'){
alignedSeqPenalty +="2";
}else if(alignedSeqA.charAt(i)!=alignedSeqB.charAt(i)){
alignedSeqPenalty +="1";
}
}
and here is my error
这是我的错误
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 10
at java.lang.String.charAt(Unknown Source)
at New.main(New.java:124)
when i changed my alignedSeqA.length()
with an integer
(like 7) it works just fine
当我alignedSeqA.length()
用一个integer
(比如 7)改变我的时候它工作得很好
i.e. --> output when i change it to 7 20100201
即 --> 将其更改为 7 时的输出20100201
what am i doing wrong?
我究竟做错了什么?
Thank you
谢谢
采纳答案by BobTheBuilder
You need to use:
您需要使用:
for (int i = 0; i < alignedSeqA.length(); i++) {
As first index is 0
and last is alignedSeqA.length() - 1
因为第一个索引是0
,最后一个是alignedSeqA.length() - 1
回答by Prabhakaran Ramaswamy
The issue is here:
问题在这里:
i <= alignedSeqA.length();
|
Remove this `=` from the for loop condition
It should be like this:
应该是这样的:
i < alignedSeqA.length();
回答by Maroun
In Java (and most programming languages), arrays are zero-based.
在 Java(和大多数编程语言)中,数组是从零开始的。
i <= alignedSeqA.length()
Should be
应该
i < alignedSeqA.length()
↑
Meaning that if you have an array of size N
, the indexes will be from 0
to N - 1
(total sum will be N
).
这意味着如果您有一个 size 数组N
,则索引将从0
到N - 1
(总和将为N
)。
To better explain it, let's take a specific example. Say alignedSeqA
is of size 5, it looks like this:
为了更好地解释它,让我们举一个具体的例子。说alignedSeqA
是大小 5,它看起来像这样:
0 1 2 3 4
+-------------------+
| | | | | |
+-------------------+
So if you loop until (include) the size (which is 5), you're out of bounds.
所以如果你循环直到(包括)大小(5),你就出界了。