您好我正在创建一个算法来获取int x并将其转换为所需的基数为int y。 例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);
}
}
在String回答它有错误找不到符号 - 变量首先,任何人都可以解释为什么它找不到它?并提供解决方案。提前谢谢
答案 0 :(得分:3)
超出范围。你在while循环中声明了它。事后不见了。
要解决此问题,请在while循环开始之前声明第一个和第二个。
答案 1 :(得分:3)
这些变量超出了范围。
在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);
}
您可能是初学者:详细了解block and statements
答案 2 :(得分:2)
变量“first”的范围以while块为界。所以它不能在它之外访问。
答案 3 :(得分:0)
你的第一个和第二个变量在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);
}
答案 4 :(得分:0)
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);
}
答案 5 :(得分:0)
您的变量first
和second
也在while循环中声明,因此它的生命周期在该循环中绑定。
如果您不清楚范围是什么,您应该阅读这篇有趣的幻灯片
http://classes.soe.ucsc.edu/cmps012a/Winter03-01/notes/Lecture27-4perpage.pdf
答案 6 :(得分:0)
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);
}