Millie Millie - 3 months ago 9
Java Question

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");
}
}
}
}
}

Answer

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");
     }    
   }    
 }    

}