Results 1 to 6 of 6
Thread: For to while?
- 09-08-2009, 10:21 AM #1
Member
- Join Date
- Aug 2009
- Location
- South Sweden
- Posts
- 24
- Rep Power
- 0
For to while?
Hey all
I'm trying to do a school exercise in java, and I fail at it, but it seems like my teacher doesnt know what's wrong.
I want to do a "for" to a "while"
(Primtal == true earlier in the code)
Here's the for:
Here's my try at a while:Java Code:for (int k=2; k<tal; k++) { if (tal % k == 0) { Primtal = false; } }
I dont get the while "primtal" to become false, when the for does get "primtal" to false...Java Code:int k = 2; while(k < tal) { k = k + 1; if (tal % k == 0) { Primtal = false; } }
Any help?
///Mattedatten
- 09-08-2009, 10:24 AM #2
Senior Member
- Join Date
- Aug 2009
- Posts
- 2,388
- Rep Power
- 6
Put
as the last line of the while.Java Code:k = k + 1;
- 09-08-2009, 10:27 AM #3
Member
- Join Date
- Sep 2009
- Posts
- 2
- Rep Power
- 0
the problem is the line:
k = k + 1
you do it before the test "if" - and so on your first entrance to the loop, you check it for k = 3.
In the for loop, k++ doesn't happen til you finish one iteration of the loop, and so in that first iteration k=2 and "if" is checked on this k. only after the iteration ends, k++ occurs.
So, just move k=k+1 to after the if-block.
- 09-08-2009, 10:36 AM #4
Member
- Join Date
- Aug 2009
- Location
- South Sweden
- Posts
- 24
- Rep Power
- 0
- 09-08-2009, 12:44 PM #5
Member
- Join Date
- Sep 2009
- Posts
- 6
- Rep Power
- 0
refer examples on java2examples.com
-
phoenix, all of your posts have such similarity as to suggest that you're spamming answers with plugs to a web site. Please be careful with this as this could lead to sanctions.


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks