[英]Why is my string index out of bounds sometimes?
Class Lab9 课堂Lab9
ScalesSolution s = new ScalesSolution("00100");
s.println();
s.SmallChange();
s.println();
Method SmallChange in the ScalesSolution class ScalesSolution类中的方法SmallChange
public void SmallChange() {
int n = scasol.length();
System.out.println("The length of scasol is "+ n);
//CS2004 method generates a random integer number between 0 and n
int p = CS2004.UI(0,n);
StringBuilder sb = new StringBuilder(scasol);
if (scasol.charAt(p) == '0') {
sb.setCharAt(p, '1');
} else {
sb.setCharAt(p, '0');
}
scasol = sb.toString();
}
After running the code multiple times, I sometimes get the error 多次运行代码后,有时会出现错误
"String index out of range 5"
Even though this prints out 即使打印出来
The length of scasol is 5
every time it is run 每次运行
Error: 00100 The length of scasol is 5 Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5 at java.lang.String.charAt(String.java:658) at ScalesSolution.SmallChange(ScalesSolution.java:15) //point to if (scasol.charAt(p) == '0') at Lab9.main(Lab9.java:9) 错误:00100 scasol的长度为5线程“主”中的异常java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:ScalesSolution.SmallChange(ScalesSolution)处的java.lang.String.charAt(String.java:658)为5。 java:15)//指向Lab9.main(Lab9.java:9)的if(scasol.charAt(p)=='0')
I don't understand how sometimes it goes out of bounds. 我不明白有时候是怎么越界的。 Any help please? 有什么帮助吗?
Indexes' numbers start from 0, so if the code below generates the numbers between 0 and 5, it won't work for a string that has 5 characters (only indexes 0 to 4 will work). 索引的数字从0开始,因此,如果下面的代码生成的数字在0到5之间,则它不适用于包含5个字符的字符串(仅索引0到4将起作用)。
//CS2004 method generates a random integer number between 0 and n
int p = CS2004.UI(0,n);
Change that to 更改为
int p = CS2004.UI(0,n-1);
Strings start with array index 0. A string with length 5 has the indices 0, 1, 2, 3, 4. By reading from the 5th index with scasol.charAt(p) == '0'
, you are reading from a part of the string that is out of bounds. 字符串以数组索引0开头。长度为5的字符串具有索引0、1、2、3、4。通过使用scasol.charAt(p) == '0'
从第5个索引进行读取,您正在读取部分超出范围的字符串。
To fix the issue, just make the index value 1 lower: scasol.charAt(p-1) == '0'
若要解决此问题,只需降低索引值1: scasol.charAt(p-1) == '0'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.