简体   繁体   中英

boolean in nested for loops

I'm a total newbie to the java world. 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 ???

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. 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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