hydregion - 1 year ago 67

Java Question

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;

System.out.println("Enter your low number");

num = input.nextInt();

System.out.println("Enter your high number");

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++;

}

}

}

Answer

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

add some mathematical knowledge:

a number n is prime, if it's not divisible by any number in range [2,n)

and we wind up with

check, if a given number n isn't divisible by any number in the range [2,n)

I'll leave figuring the rest out to you.

Thanks for being honest and making clear this is homework.

Source (Stackoverflow)