user2797454 user2797454 - 3 months ago 14
Java Question

Cannot find symbol while loop

Hello I am creating an algorithm to take int x and convert it to the desired base being int y.
example 7 base 3 = 21.

void printXBaseY(int x, int y) {

boolean active = true;

while(x >= y) {
int a = x % y;
int b = x / y;


String first = "" + a;
String second = "" + b;

String answer = "" + first + second;

}

String answer = "" + first + second;

println(x + " base " + y + " is " + answer);

}


}

at String answer it has error cannot find symbol - variable first, can anyone explain why it cannot find it? and provide a solution.

thank you in advance

Answer

Those variable's are out of scope.

In java the scope is restricted to {}.

Just move them to top, so that they're available further.

void printXBaseY(int x, int y) {

          boolean active = true; 
          String first=""; //  or null
          String second=""; // or null 
          while(x >= y) {
              int a = x % y;
              int b = x / y;


               first = "" + a;
               second = "" + b;

              String answer = "" + first + second;

          }

          String answer = "" + first + second;

          System.out.println(x + " base " + y + " is " + answer);

        }

You might be a beginner :Read more about block and statements