dde*_*ral 2 java arrays iteration
我想要的输出是储物柜1,4,9,16,36,49,81 和 100.我正在试图找到学生被送到后的哪些储物柜,并打开每个储物柜.(默认情况下全部关闭)并打开每个储物柜.然后学号2进入其他每个储物柜,如果它打开,关闭它,如果它关闭,打开它.学生三做同样但每三个储物柜.一直到学生100.我知道输出应该是所有的方形数字,但我不能得到100出现.我错过了什么?我在我的两次迭代中都设置了一个<=并且它不起作用.它抛出IndexOutOfRangeException.我该怎么办?
import java.util.Arrays;
public class runLocker {
final static int numberOfLockers = 100;
final static int numberOfStudents = 100;
public static void main(String[] args) {
// TODO Auto-generated method stub
int LockersToCloseBy = 1;
boolean[] totalLockersArray = new boolean[numberOfLockers];
for(int i = 0; i < totalLockersArray.length - 1; i++){
totalLockersArray[i] = false;
}
for(int n= 0; n < totalLockersArray.length ; ++n){
for(int j = 0; j < totalLockersArray.length; j+=LockersToCloseBy){
if(totalLockersArray[j] == true)
{
totalLockersArray[j] = false;
}
else
{
totalLockersArray[j] = true;
}
}
LockersToCloseBy++;
}
for(int i = 0; i < numberOfLockers; i++){
if(totalLockersArray[i] == true){
System.out.println("Locker " + i + " is open");
}
}
//Currently outputs 1, 4, 9, 16, 36, 49, and 81...
//Need it to output 1,4,9,16,36,49,81,100
}
Run Code Online (Sandbox Code Playgroud)
}
您的数组是为索引[0,...,99]定义的(总共100个元素,不包括100个).
在以下代码中:
for(int i = 0; i < numberOfLockers; i++){
if(totalLockersArray[i] == true){
System.out.println("Locker " + i + " is open");
}
}
Run Code Online (Sandbox Code Playgroud)
100甚至不是候选人.
一个简单的解决方法是将锁定器数组设置为101(numberOfLockers = 101),因此所有循环都将包含100.