1

The error is "cannot find symbol variable b" I'd like to understand as well how to correctly write the syntax of the do while loop Thanks.

import java.util.*;

public class pract3ex10 {

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        do {
            System.out.println("Enter a positive");
            int n = s.nextInt();
            int x = n;
            int m = 0;
            if (x < 0) {
                System.out.println("Thank You!");
            } else {
                while (x > 0) {
                    x = x / 10;
                    m++;
                }
                System.out.println("Number of digits in " + n + "= " + m);
            }
        } while (n > 0);

    }

}
Pshemo
  • 122,468
  • 25
  • 185
  • 269
  • 2
    where is variable b in code? – Ankit Apr 15 '13 at 18:12
  • You will need this [The while and do-while Statements](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html) – Smit Apr 15 '13 at 18:13
  • When I compile your code in Java7 I get `n cannot be resolved to a variable` and it seems correct since `n` is defined inside `do{..}while` loop so it is out of scope for `while` condition. Maybe try to declare `int n=-1` before loop. – Pshemo Apr 15 '13 at 18:15
  • A specific case of the general question http://stackoverflow.com/questions/25706216/what-does-a-cannot-find-symbol-compilation-error-mean – Raedwald Feb 26 '16 at 20:10

3 Answers3

2

The scope of the n variable is currently only inside the do-while block, within the braces. If you would like it to be accessible in a bigger scope, even if that means the condition for the loop, then declare it outside the loop.

int n;
do
{
    n = s.nextInt();
    ...
rgettman
  • 176,041
  • 30
  • 275
  • 357
1
int n;
do {
    ...
    n = s.nextInt();
    ...
} while (n > 0);
sp00m
  • 47,968
  • 31
  • 142
  • 252
1

n should be declared before of the do..while block...

elopez
  • 109
  • 9