这是我对本网站的第一个问题所以我很抱歉,如果我发布错误的内容,我会很感激!这是一个功课问题,虽然我似乎无法以这种方式标记它.
无论如何,代码看起来编译得很好(使用BlueJ)但是在我运行它时进入第一个while循环时会卡住.我添加了一些输出行来查看问题发生的位置和第一个System.out进入第一个while循环时从未发生... JVM只是继续工作,直到我强制它重置.我相信我的初始while循环应该运行4次然后退出我使用的值(5名学生,我从2开始),但它似乎没有做任何事情,我不知道我是什么做错了.
完成后程序要执行的操作的摘要.
一系列学生走过一排储物柜.
学生1打开所有储物柜
学生2关闭每一个储物柜
学生3反转每三个储物柜等的状态以获得学生人数
我知道我没有设置布尔锁定器标志正确翻转并打算在第二个while循环中使用!myBool的变体 - 但首先我要确保我的while循环工作.希望我因为长时间盯着它而错过了一些简单的东西!
import java.util.Arrays; public class Lockers { public static void main (String[]args) { // Size of lockerArray int arraySize = 5; // Set up new lockerArray boolean[] lockerArray = new boolean[arraySize]; // Variable for number of students in the exercise int studentNumber = 5; System.out.println("Student 1 opens all the lockers.\n");// Outputs, good // Student 1 opens all the lockers // Boolean values for lockerArray true = OPEN; false = CLOSED Arrays.fill(lockerArray, true); System.out.println(Arrays.toString(lockerArray)); // Outputs 5 true, good // Set the student counter at 2 (Student 1 has already made their pass) int i = 2; // Loop until you run out of students while (i <= studentNumber); { System.out.println("Student Number " + i + " is making their pass.\n");// NEVER HAPPENS - have to reset JVM to stop program // Set up a variable to control the sequence required (i.e., Student 2 every second locker, // Student 3 every third locker, etc. int j = i; while (j <= arraySize); { System.out.println("Student is changing the status of locker number " + j + ".\n"); // Reverse the flag at each locker for which the statement is true for this student number // Need to reduce the variable by 1 as locker 1 would be sitting in lockerArray[0] position lockerArray[j-1] = false; // Increment locker number by the value of the student in the sequence j = j + i; } // Increment the student count i++; } // Print the final array status System.out.println(Arrays.toString(lockerArray)); } }
Makoto.. 8
你的while
循环后面有分号.
while (i <= studentNumber);
这导致无限循环,因为您的i
变量无法更改.