这个程序应该创建一个包含150个“邮箱”的布尔数组。第一个for循环应该将它们都设置为false定义的"closed“。第二个for循环应该从第二个邮箱index[1]开始,每隔一次打开一次。第三个和第四个for循环应该从第三个邮箱index[2]开始,每隔三次打开一次,然后在到达第150个之后,返回到第四个for循环,每隔三次打开一次。最后的for循环应该打印出哪个for循环是闭合的。我还没能让它跑过17行。
public class CS2LAB1 {
public static void main(String[] args)
{
boolean[] mailboxes = new boolean[149];
/*this function sets all mailbox doors to closed*/
for(int i = 0; i <= mailboxes.length; i++)
{
mailboxes[i] = false;
}
/*This function uses a for loop to begin at mailbox 2 and open every even mailbox
*/
for(int count = 1; count <= mailboxes.length; count = count + 2)
{
mailboxes[count] = true;
}
/*This function starts at 3 and opens every 3rd mailbox, next it goes to 4 and opens every 3rd mailbox followed by the 4th then 5th then 6th */
for(int count2 = 2; count2<=mailboxes.length; count2++)
{
for(int count3 = count2; count3 <= mailboxes.length; count3 = count3 + count2)
{
if(mailboxes[count2] = true)
{ mailboxes[count2] = false;}
else{ mailboxes[count2] = true;}
}
}
/*This function outputs all the closed doors*/
for(int print =0; mailboxes.length>=print; print++)
if(mailboxes[print] = false)
{
System.out.println("Mailbox" + print++ + "is closed" );
}
}}
更新:我检查并更改了boolean的值,现在closed等同于true,open用于false,因为任何boolean数组都已经设置为false。我没有得到正确的输出,而是程序输出了所有打开的邮箱
此外,我相信我已经将问题缩小到嵌套的for循环。里面的if statements从来没有被使用过,我不明白为什么。有什么想法吗?
for(int count2 = 2; count2<= 149; count2++)
{
for(int count3 = 2; count3 <= 149; count3 = count3 + 3)
{
if(mailboxes[count3] = false)
{ mailboxes[count3] = true;}
else{ mailboxes[count3] = false;}
}
}发布于 2019-01-15 10:42:19
您的第一个for循环可能抛出了IndexOutOfBoundException。在Java语言中,数组是0索引的,这意味着它们从0开始,一直到Array.length - 1。因此,为了遍历整个数组,需要从for(int i = 0; i < arr.length; i++)开始迭代。
您的for循环正在从for(int i = 0; i <= mailboxes.length; i++)遍历。这意味着当数组索引从[0, ..., 148]开始时,索引i的最后一个值是149。
https://stackoverflow.com/questions/54191935
复制相似问题