简体   繁体   English

嵌套循环中的布尔值

[英]boolean in nested for loops

I'm a total newbie to the java world. 我是Java世界的新手。 I came across a code such as presented below: 我遇到了如下所示的代码:

public static void main (String [] args){
    int x,y;
    boolean isprime;

    for (x=2; x<100; x++) {
        isprime=true;

        for (y=2; y<=x/y;y++) 

        if ((x%y)==0) isprime = false;
        if (isprime) System.out.println (x + " is a prime number");
    }   
}

My question is: Does the boolean isprime=true relate to the x in a way that each x is true unless later it is false if x%y==0 ??? 我的问题是:boolean isprime=true是否以每个x为真的方式与x相关,除非以后如果x%y==0则为false?

I don't quite get it. 我不太明白。

As others have pointed out, you have answered your own question correctly. 正如其他人指出的那样,您已经正确回答了自己的问题。 Additionally, the spacing and lack of braces is confusing but a for loop without braces only affects the next line. 此外,花括号的间距和缺乏是令人困惑的,但是没有花括号的for循环只会影响下一行。 This is what the code would look like with the curly braces included: 包含花括号的代码如下所示:

public static void main (String [] args){
    int x,y;
    boolean isprime;

    for (x=2; x<100; x++) {
        isprime=true;

        for (y=2; y<=x/y;y++) {
            if ((x%y)==0) isprime = false;
        }
        if (isprime) System.out.println (x + " is a prime number");
    }   
}

Hope this helps! 希望这可以帮助!

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

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