hydregion - 6 months ago 26
Java Question

# I need to display prime numbers between two numbers

I have a school assignment where I need to prompt the user for two numbers and display all the prime numbers in between I can't figure it out for the life of me. Here is my code, all it does is end as soon as I enter the two numbers.

``````public static void pg150Exersize1B() {
Scanner input = new Scanner(System.in);
int num, counter, num2;
num = input.nextInt();
num2 = input.nextInt();
counter = num;
while (num != num2) {
counter++;
if (num % counter == 0) {
if (counter == num) {
System.out.println(counter);
num++;
} else {
num++;
}
} else{
num++;
}
}

}
``````

The first step in solving any coding-problem would be to transform the textual task into a basic code structure.

As an example, we can translate the task into the following main-routine:

display all prime numbers between two given numbers

could be translated to

print all numbers in a given range, if they are prime

which can be translated to the following pseudocode:

``````for i in [lower,upper]
if isPrime(i)
print(i)
``````

This pseudocode can be translated pretty simple into the correct java-code.

Now we're missing one additional piece: the function `isPrime(...)`. So let's apply the same pattern:

check, if a given number is prime