我需要打印 32 位二进制数的所有实例,其中没有两个 1 彼此相邻。
例如:
10101010101010000000101010101010 is valid
01010101010110000000000000000000 is not because there are adjacent 1s
这是我所拥有的。
String number;
boolean valid = false;
for(int i = 0; i<= 1e32; i++)
{
//create binary number
number = String.format("%32s", Integer.toBinaryString(i)).replace(' ', '0');
for(int k = 0; k <= number.length() - 1; k++)
{
//check if there are adjacent 1s
if((number.charAt(k) == '1') && (number.charAt(k+1) == '1'))//I believe error is from this line
{
valid = false;
}
else
{
valid = true;
}
}
if(valid == true)
{
//Print if there are no adjacent 1s
System.out.println(number);
valid = false;
}
}
这是我收到的索引错误。我相信错误来自于检查相邻 1 的索引时,但我无法弄清楚为什么它超出范围。有人可以帮忙吗?
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 32
at java.lang.String.charAt(String.java:658)
at program.program.main(program.java:30)
Java Result: 1
最佳答案
尝试使用:
for(int k = 0; k < number.length() - 1; k++)
行:
number.charAt(k+1)
将超出当前设置的范围,移过数组中的最后一个元素。
关于java - 查找重复相邻元素时字符串索引超出范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22238699/