having a little trouble with my code this is for a class so maybe more suggestion help then direct unless its a small mistake thank you!

im making a loop to generate a random number between 2-128 then trying to find if its primeint p;

int function;

boolean isPrime;

double formattedP;

while(isPrime= false)

formattedP = Math.random() * 126 + 2;

p = (int) formattedP;

isPrime = true;

for (int i = 2; i < p; i++) {function = p % i;

if (function == 0) {

isPrime = false;

}

}

System.out.println(p + " " + isPrime);}its telling me fomattedP is never intilized when tyring to plug it into p and casting it to an int

Then let's reformat your code to make the problem clearer. isPrime = false; while(false) { formattedP = Math.random() * 126 + 2; }

See it yet?

if i put curly brackets around formattedP it still tells me it is never intilazied when it comes to casting it into p

i do know that what is wrong is very small haha sighint p;

int function;

boolean isPrime = false;

double formattedP;

while(isPrime = false)

formattedP = Math.random() * 126 + 2;

p = (int) formattedP;

isPrime = true;

for (int i = 2; i < p; i++) {function = p % i;

if (function == 0) {

isPrime = false;

}

}

System.out.println(p + " " + isPrime);}}

I haven't test this as I do not have any c/java compilers installed but how about you try casting formattedP when you generate the random values? i.e.

while(isPrime = false)

(int) formattedP = Math.random() * 126 + 2;

out.println(formattedP); // print formattedP to see what it looks like

p = formattedP;> Option 2

while(isPrime = false)

formattedP = (int)Math.random() * 126 + 2;

out.println(formattedP); // print formattedP to see what it looks like

p = formattedP;

Try both options but i'm more confident with option 2.

haleyrt:i put curly brackets around formattedP

Oh, you misunderstand. I'm pointing out what you did, not telling you what you need to do.Here's what your code compiles down to:

double formattedP; isPrime= false; p = (int) formattedP;

so its not putting in the random interger? why is that?

Because while (false)will never run. The language does the loop test before running the while loop, and the test is false.

so how do i make a loop that runs my code until it finds a prime number?

Initialize your boolean earlier in your code, change your test to test for not isPrime, and wrap everything in the function below the while line in braces (otherwise you'll just end up in an endless loop). Also, fix your prime check, or your code will always say the number is prime.

Ask Your Question

Weekly Poll

Do you think Google should sell budget phones in the US?

Discuss in The Lounge

Poll History