Dobhaweim
Dobhaweim

Reputation: 163

Do-While loop in Java

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

Answers (3)

Woot4Moo
Woot4Moo

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

Ramesh Kotha
Ramesh Kotha

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

Hovercraft Full Of Eels
Hovercraft Full Of Eels

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

Related Questions