# Help with loops

October 3, 2009 at 12:43:49
Specs: Windows Vista
 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 prime int 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

See More: Help with loops

#1
October 3, 2009 at 12:48:55
 Then let's reformat your code to make the problem clearer.```isPrime = false; while(false) { formattedP = Math.random() * 126 + 2; }```See it yet?

Report •

#2
October 3, 2009 at 13:04:25
 if i put curly brackets around formattedP it still tells me it is never intilazied when it comes to casting it into pi 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);}}

Report •

#3
October 3, 2009 at 13:34:00
 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.

Report •

Related Solutions

#4
October 3, 2009 at 13:47:43
 haleyrt: i put curly brackets around formattedPOh, 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;```

Report •

#5
October 3, 2009 at 13:49:41
 so its not putting in the random interger? why is that?

Report •

#6
October 3, 2009 at 13:59:46
 Because while (false) will never run. The language does the loop test before running the while loop, and the test is false.

Report •

#7
October 3, 2009 at 14:06:05
 so how do i make a loop that runs my code until it finds a prime number?

Report •

#8
October 3, 2009 at 14:54:09
 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.

Report •