-4

Here is the simple code

package first;

public class DowhileLoops {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        do {
            int i = 1;
            i++;
            System.out.println("my loop is working ");

        }while(5 > i);
    }
}

Here is the Error

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
i cannot be resolved to a variable
at todowhileloops/first.DowhileLoops.main(DowhileLoops.java:15)

I khow that the variable must be defined outside instead of inside the loop but i want to know whyyyyy... please help and vote the question.

deadshot
  • 8,881
  • 4
  • 20
  • 39

3 Answers3

2

Define i outside do statement. From your current code the scope of i is only inside do{}. It is a local variable for do. It's not accessible to while().

omar jayed
  • 850
  • 5
  • 16
1

The while conditional only has access to "current" variable scope. The do block creates a "child" variable scope. Any variables declared in a "child" variable scopes are not accessible in "parent" scopes.

See "Loop Scope" in https://www.java-made-easy.com/variable-scope.html for a more detailed explanation.

blurfus
  • 13,485
  • 8
  • 55
  • 61
jsotelo
  • 11
  • 2
1
do {
    int i = 1;
    i++;
    System.out.println("my loop is working ");
} while(5 > i);

Ok, so first off, you have to initialize the variable outside of the loop itself. so before you write "do {". right now you're setting i to 1 every iteration, meaning this loop will never terminate. Here you go:

int i = 0;
do {
    i++
    System.out.println(i);
} while (i < 5);
JoeChris
  • 231
  • 1
  • 9