简体   繁体   中英

Got the break statement to work, but can't figure out the java for condition

I'm trying to figure out how to do the primes from 1 to 101. I've got this so far:

public class BreakShow{
  public static void main(String[] args){
  int i;
  int prime;

  System.out.println("Prime numbers from 1 to 101 : ");
    for (i = 1;i < 102;i++ ){
        for (prime = 2;prime < i;prime++ ){
            if(i % prime == 0) {
                break;
            }
        }
        if(i == prime) {
            System.out.print("  " + i);
        }
    }
  }
}

I can't get it to print the 1. I've tried changing the values for i and prime around, but it doesn't work. Seems to be linked with the print and it's just not continuing. I guess I don't really understand the conditions of the for statement and how it operates.

What's happening is that when i is = 1 (when you're testing for the case of 1), this loop:

for (prime = 2;prime < i;prime++ ){
    if(i % prime == 0) {
        break;
    }
}

Never runs, because prime is never actually less than i, because prime starts at 2. Which means it then checks if i == prime, which it will never be, since prime = 2.

prime variable is initialized with value 2 but you are checking 1==2.

you can test value i and prime before if condition

System.out.println("i:: "+ i+ "  prime:: "+prime);
    if(i == prime) 
        {
            System.out.print("  " + i);
        }

so if clause  does not meet the condition 

Java knows that 1 is not a prime and doesn't print it.

First two google results for 'is 1 a prime number' prove it.

If you are trying to do fizz buzz with prime, then you should only need one loop and mod by 2. You could just do something like this.

for(int i = 1; i <= 101; i++){
   if( (i%2) != 0) // use the smallest even number to check against.
      println("prime");
}

Since second for loop starts with 2, its skipping 1 because of i==prime condition before print. If you really want to print 1, Please update your conditions as below:

     public static void main(String[] args) {
          int prime;
          System.out.println("Prime numbers from 1 to 101 : ");
            for (int i = 1;i < 102;i++ ){
                for (prime= i-2;prime > 1;prime-- ){
                    if(prime< 0 || i % prime == 0) {
                        break;
                    }
                }
                if(prime < 0 || prime==1) {
                    System.out.print("  " + i);
                }
           }
      }

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