循环时找不到符号



您好,我正在创建一个算法来获取int x并将其转换为所需的int y基数。示例 7 基数 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);
}

}

在字符串答案它有错误找不到符号 - 变量首先,谁能解释为什么它找不到它? 并提供解决方案。

提前谢谢你

这些变量超出了范围。

在 java 中,范围仅限于 {}

只需将它们移动到顶部,以便进一步使用它们。

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);
        }

您可能是初学者:阅读有关块和语句的更多信息

它超出了范围。您在 while 循环中声明了它。之后就不见了。

要解决此问题,请在 while 循环开始之前声明第一个和第二个。

变量"first"的作用域以 while block 为界。因此,无法在其外部访问它。

您的第一个和第二个变量在 while 循环中声明。所以它们的范围在 while 循环内部,只有你不能在 while 循环之外使用它们。

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

      first = "" + a;
      second = "" + b;
      String answer = "" + first + second;
  }
  String answer = "" + first + second;
  println(x + " base " + y + " is " + answer);
}
 while(x >= y) {
     int a = x % y;
     int b = x / y;

     String first = "" + a;  // here is the problem. You declared first and second within the while loop.
     String second = "" + b;
     String answer = "" + first + second;
 } 

更正了以下代码

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);
 }
变量

firstsecond也在 while 循环中声明,因此其生存期绑定在该循环中。如果您不清楚示波器是什么,您应该阅读这张有趣的幻灯片http://classes.soe.ucsc.edu/cmps012a/Winter03-01/notes/Lecture27-4perpage.pdf

void printXBaseY(int x, int y) {
  boolean active = true;   
 String first="";    
String second="";   
  String answer="";     
  while(x >= y) {  
      int a = x % y;  
      int b = x / y;  

       first = "" + a;
      second = "" + b;
   //  answer = "" + first + second;
  }
  answer = "" + first + second;
  println(x + " base " + y + " is " + answer);
}

相关内容

  • 没有找到相关文章

最新更新