Reputation: 407
For some reason, my second for loop will NOT run at all. In fact, any other type of for loop I put in there wont run either. I tested just putting a simple for loop right after the println("looping until we divide by...); and that wouldnt run either. The simple for loop I added for testing was this.
for (int k = 0; k > 10; k++) {
System.out.println(k);
}
Which would obviously just print the values from 0 to 10. But it wont execute. Here is the actual code for the program. In case anyone is wondering what it is supposed to do, it takes a range, hardcoded for testing to be from 100 to 1000. It checks to see if the last number, 1000, is a prime by looping through all numbers from 2 to 1000/2 to see if the remainder is 0, if it is, the number is not a prime, break the loop and check the next number. If the number makes it through without setting isPrime to false, then it is a prime, and because we start with the largest number, it is the largest prime number in the list and therefor we break the outer loop and print it. Yes this is part of a homework assignment using RMI. I have the RMI working completely fine but the algorithm was giving me trouble so I decided to start with a fresh program and get the algorithm right before I put it into my PrimeImpl class. Here is the code.
public class PrimeTest {
public static void main(String[] args) {
int first = 100;
int last = 1000;
int biggest = 0;
boolean isPrime = true;
int i;
for (i = last; i > first - 1; i--) {
isPrime = true;
System.out.println("Assume " + i + " is prime.");
int halfI = i / 2;
System.out.println("Looping until we divide by " + halfI);
for (int j = 2; j > halfI; j++) {
// Loop not entering. This statement doesnt print. Why?
System.out.println(i + " modulus " + j + " = " + i % j);
if (i % j == 0) {
isPrime = false;
System.out.println("Not a prime");
break;
}
}
if (isPrime == true) {
System.out.println(i + " is a prime");
break;
}
}
if (isPrime == true) {
biggest = i;
}
if (isPrime == false) {
biggest = 0;
}
System.out.println(biggest);
}
}
I know there are other ways to test numbers for prime, but for the time being I would like to try and use my method here. It seems that it would be efficient IF it works because as soon as I get the first prime number, its done.
Upvotes: 1
Views: 169
Reputation: 66657
for (int k = 0; k > 10; k++) {
System.out.println(k);
}
k
is not greater than 10, so loop will will never execute. I think what want is k<10
, isn't it?
for (int k = 0; k < 10; k++) {
System.out.println(k);
}
Upvotes: 4