paulllt paulllt - 13 days ago 5
Java Question

What am I missing in my Java blocks?

Newbie here. I have a program that extract prime numbers from numbers 1-100. The code below compiles but gives a blank output when interpreted.

However, when I omit the pair of curly braces in the nested for-block (2nd for-block), it'll give the correct output.

I also tried this in C++ and the issue is the same. Am I missing something here? Thanks in advance.

public class PrimeNumbers {
public static void main (String args[]) {
int i, j;

for(i=2;i<=100;i++) {

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

if(j > (i/j)) {
System.out.println(i);
}
}
}
}
}


And here's my code in C++, the issue is the same with the 2nd for-block

#include <iostream>
using namespace std;

int main() {
int i, j;
for(i=2;i<=100;i++) {
for(j=2;j<=(i/j);j++) {
if(!(i%j))
break;
if(j > (i/j))
cout << i;
}
}
return 0;
}

Answer

Ok. Here how you can check for prime numbers between 2 and 100.

public class PrimeNumbers {

public static void main(String args[]) {
    int i, j;

    for (i = 2; i <= 100; i++) {
        boolean prime = true;
        for (j = 2; j < i; j++) {
            if (i % j == 0) {
                prime = false;
                j=i;
            }
        }
        if (prime) {
            System.out.println(i + " is prime");
        }
    }
}

Regarding your code, close the nested for loop before second if. So edit your code as below:

public class PrimeNumbers {

public static void main(String args[]) {
    int i, j;

    for (i = 2; i <= 100; i++) {

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

        if (j > (i / j)) {
            System.out.println(i);
        }
    }
}
}
Comments