简体   繁体   中英

Correctly Printing For Loops in Java

I have been working on this program for a few hours and the code is working correctly but I can't seem to get it to print out correctly, it should just be printing once for each value, such as:

number: 6

dividers: 2 3 6 1

prime: is not prime

Output

Can anyone help? Screenshot is attached. Thanks!

public static void main(String[] args) {

    Random randomNums = new Random();

    int count;

    for (int i = 1; i <= 37; i++) { 

      count = randomNums.nextInt(100) + 1;
      System.out.println("number " + count); 

    for (int b = 1; b<=count; b++) {
        if (count % b == 0) {
            System.out.println("dividers " + b);
        }

    }
    for (int a = 2; a< count; a++) {
        if (count % a == 0) {
             System.out.println("is not prime");   
         }
         if (count % a != 0) {
             System.out.println("is prime");
         }
       }    
     }    
   }    
 }

based upon your logic, I am guessing that if you decide that a number is not a prime then that is the final result,

so

boolean isPrime = true;
String dividers = "";
for (int a = 2; a< count; a++) {
    if (count % a == 0) {
         isPrime = false;
         dividers += a+" ";
     }
} 

if (isPrime) {
  System.out.println ("is Prime");
} else {
  System.out.println ("dividers "+dividers);
  System.out.println ("is not Prime");
}

try to write this code :

 public static void main(String[] args) {

    Random randomNums = new Random();

    int count;

    for (int i = 1; i <= 37; i++) { 

      count = randomNums.nextInt(100) + 1;
      System.out.println("number " + count); 
    String dividers = "";
    for (int b = 1; b<=count; b++) {
        if (count % b == 0) {
            dividers += b.toString() +" ";
        }

    }
    // control the print beside loop
    System.out.println("dividers " + dividers);
    // add the control for whether prime
    bool prime = true;
    for (int a = 2; a< count; a++) {
        if (count % a == 0) {
             System.out.println("prime : is not prime");
             // add the control for skip loop
             prime = false;
             break;   
         }
     }
     if(prime){
     System.out.println("prime : is prime");
     }    
   }    
 }    

}

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