Reputation: 163
So, as far as I understand it, a do while loop will always run at least once? But if this is the case why do we need to declare and initialise variables outside of the loop?
Take for instance the following code:
do {
int a = (int) (Math.random() * 13);
int b = (int) (Math.random() * 13);
int c = (int) (Math.random() * 13);
int d = (int) (Math.random() * 13);
}
while (a + b + c + d != 24);
Which will throw a compile error that a, b, c, d may not have been initialised. As I'm a java beginner I'm sure there's a simple reason for this, but I cannot seem to find it?!
Much thanks for any help with this.
Upvotes: 2
Views: 376
Reputation: 24316
do {
int a = (int) (Math.random() * 13);
int b = (int) (Math.random() * 13);
int c = (int) (Math.random() * 13);
int d = (int) (Math.random() * 13);
}
while (a + b + c + d != 24);
This is a scoping issue. Look at jls 6.3. Scope of a Declaration
You want to re-write the code as so:
int a = 0; //I am being explicit here
int b = 0;
int c = 0;
int d = 0;
do {
a = (int) (Math.random() * 13);
b = (int) (Math.random() * 13);
c = (int) (Math.random() * 13);
d = (int) (Math.random() * 13);
}
while (a + b + c + d != 24);
Upvotes: 0
Reputation: 8322
This can be re written like this
int a = (int) (Math.random() * 13);
int b = (int) (Math.random() * 13);
int c = (int) (Math.random() * 13);
int d = (int) (Math.random() * 13);
while (a + b + c + d != 24){
a = (int) (Math.random() * 13);
b = (int) (Math.random() * 13);
c = (int) (Math.random() * 13);
d = (int) (Math.random() * 13);
//do something
}
Upvotes: 1
Reputation: 285405
Look up variable scope because that is your problem: you're trying to access variables outside of their declared scope, here the do-while loop, and this cannot be done.
Note your code will work if you introduce one more variable:
int sum = 0; // scope is *outside* of do-while loop
do {
int a = (int) (Math.random() * 13);
int b = (int) (Math.random() * 13);
int c = (int) (Math.random() * 13);
int d = (int) (Math.random() * 13);
sum = a + b + c + d;
} while (sum != 24);
But note that now if you still need to access the a, b, c, and d values, you cannot. To allow this, again, you should declare your variables before the loop.
Upvotes: 3