简体   繁体   中英

Why doesn't this loop print?

I am trying to print numbers that are divisible by 5, that goes all the way up to 500.
However, nothing gets printed out in my current program.

Code:

public class Messin {
    public static void main (String[] args) {
        for (int prime = 5; prime == 500; prime++ ) {
            if (prime % 5 != 0 )
                System.out.print(prime);
        }  
    }
}

Change your for loop to:

for (int prime = 5; prime <= 500; prime++ ) {
    // ...
}

The problem with your original for loop is that, the initial value doesn't satisfy the loop condition (prime == 500), and hence it doesn't run at all.

And to find numbers divisible by 5, it should be:

if (prime % 5 == 0)

A number with remainder 0 when divided by 5, is well.. divisible by 5.

prime == 500 // false as prime contain 5 not 500

is wrong, because you declare int prime = 5 . So loops does not iterate for a single time!

Try this:

for (int prime = 5; prime <= 500; prime++ ) {
....

Moreover,

I'm trying to print numbers that are divisible by 5

So change

if (prime % 5 !=0 )

to

if (prime % 5 == 0) 

because if prime is divisible by 5 then the remainder will be 0 .

您可能希望prime==500成为prime <= 500

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