简体   繁体   English

我的for循环怎么了?

[英]What is wrong with my for-loop?

public class Lockers {

    public static void main(String[] args) {
        boolean[] lockers = new boolean[100];
        int num = 2;
        for(int a=0; a < 100; a++) {
            lockers[a] = true;
        }

        for(int num=1; num < 101; num++) {

            for(int i=1; i < 100; i = i+num) {
                if (lockers[i]) {
                lockers[i] = false;
                    }
                else {
                    lockers[i] = true;
                    }
        }}

        for(int i=0; i < 100; i++) {
            if (lockers[i]) {
                System.out.print("Opened");
                }
            else {
                System.out.print("Closed");
                }
        }

}}

So this program is out of my java textbook for school, the idea is there are 100 lockers all open now starting at the second locker close every 2nd one. 所以这个程序不在我学校的Java教科书中,想法是现在有100个储物柜全部打开,从第二个储物柜开始,每第二个储物柜关闭一次。 (2,4,6,8,10) Then restarting at the second locker go through with every 3rd locker doing the same (opening a closed locker, or closing an open one). (2,4,6,8,10)然后在第二个储物柜中重新启动,每个第三个储物柜都执行相同的操作(打开一个封闭的储物柜,或关闭一个打开的储物柜)。 Now my third for-loop seems to be my issue it will not function for some reason, the second for-loop is included so when the third for-loop starts it goes through every 2nd locker then back to the second for-loop statement it increases "num" by 1 goes through ever 3rd then 4th and so on and so forth. 现在我的第三个for循环似乎是我的问题,由于某种原因它不会起作用,因此包含了第二个for循环,因此当第三个for循环启动时,它会经过每个第二个储物柜,然后返回到第二个for循环语句中将“ num”增加1会经过3到4,依此类推。 i would like to only use the basic commands i have learned so far in java and in the program now, so please help me solve this problem without really advanced coding. 我只想使用到目前为止在Java和程序中学到的基本命令,所以请帮助我解决此问题而无需真正的高级编码。

The problem is that when i run the program the third for-loop is an infinite loop, i know the first two loops run fine, i tested that by after the second for-loop i made it output the "num" and it outputs all numbers 2 through 100 like i want but then the loop is endless at the third for-loop, not outputting anything else 问题是,当我运行程序时,第三个for循环是一个无限循环,我知道前两个循环运行良好,我测试了在第二个for循环之后我将其输出为“ num”,并输出了所有像我想要的2到100的数字,但是循环在第三个for循环中无休止,没有输出任何其他内容

I am not so good wtih java, so I will tell you what I think from my knowlage at C#. 我对Java不太满意,所以我将根据C#的知识告诉您我的想法。

In your last for loop you are writing i=i++ , what you need to write is this: i=i+1 在您的最后一个for循环中,您正在编写i=i++ ,您需要编写的是: i=i+1

this is what i think .... try that tell me if that works for you 这就是我的想法....尝试告诉我是否对您有用

Is it as simple as: 是否简单如:

for(int i=0; i < 100; i = i++) for(int i = 0; i <100; i = i ++)

should be: 应该:

for(int i=0; i < 100; i++) for(int i = 0; i <100; i ++)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM