我正在写一个方法来分解一个数字,由于某种原因,当我尝试打印factorA时,它显示它不被识别,有什么建议吗?
public static void factorize(int n){
if (n % 2 == 0){ //If number is even
int factorA = 2;
int factorB = n/2;
}else{ //If number is odd
int halfLine = n/2; //Only variables that are even will be factors greater than half of them, this case is only for odd integers
int smallestFactorOdd = 3;
while (smallestFactorOdd < halfLine){ //Until you've found the smallest factor for add variables
if (n % smallestFactorOdd == 0){ //If smallestFactorOdd is a factor of n
int factorA = smallestFactorOdd;
int factorB = n/smallestFactorOdd;
}else{
smallestFactorOdd += 2;
}
}
}
System.out.println(factorA);
}
已更新代码(仍在接收错误):
public static void factorize(int n){
int factorA;
int factorB;
if (n % 2 == 0){ //If number is even
factorA = 2;
factorB = n/2;
}else{ //If number is odd
int halfLine = n/2; //Only variables that are even will be factors greater than half of them, this case is only for odd integers
int smallestFactorOdd = 3;
while (smallestFactorOdd < halfLine){ //Until you've found the smallest factor for add variables
if (n % smallestFactorOdd == 0){ //If smallestFactorOdd is a factor of n
factorA = smallestFactorOdd;
factorB = n/smallestFactorOdd;
}else{
smallestFactorOdd += 2;
}
}
}
System.out.println(factorA);
System.out.println(factorB);
}
发布于 2018-06-02 22:28:52
声明和初始化都必须在if之外
public static void factorize(int n){
int factorA = 0;
int factorB = 0;
if (n % 2 == 0){
factorA = 2;
factorB = n/2;
}else{
int halfLine = n/2;
int smallestFactorOdd = 3;
发布于 2018-06-02 21:37:09
您可以在while
循环中声明factorA
。在循环内声明的任何变量在循环外都不存在。(其他类和方法甚至不知道变量的存在)您需要在循环外部声明变量
如下所示:
public static void factorize(int n){
int factorA = 0;
int factorB = 0;
...
编辑:
在声明变量时,必须将其设置为零。否则,它有可能永远不会被赋值。因为它是一个方法局部变量,所以在使用它之前必须对其进行初始化。(然后尝试打印它。编译器不知道该值,因此它会报错)
进一步阅读有关第二个错误的信息:
发布于 2018-06-02 22:02:07
在使用本地变量之前,必须先对其进行初始化。
你不需要只在实例变量的情况下初始化原语。
实例变量在创建该类的对象时被初始化。但是在方法的作用域中定义的变量必须初始化。
因此,在你的方法中,将0
赋值给你的局部变量,它就会起作用。
public static void factorize(int n){
int factorA = 0;
int factorB = 0;
if (n % 2 == 0){ //If number is even
factorA = 2;
factorB = n/2;
}else{ //If number is odd
int halfLine = n/2; //Only variables that are even will be factors greater than half of them, this case is only for odd integers
int smallestFactorOdd = 3;
while (smallestFactorOdd < halfLine){ //Until you've found the smallest factor for add variables
if (n % smallestFactorOdd == 0){ //If smallestFactorOdd is a factor of n
factorA = smallestFactorOdd;
factorB = n/smallestFactorOdd;
}else{
smallestFactorOdd += 2;
}
}
}
System.out.println(factorA);
System.out.println(factorB);
}
https://stackoverflow.com/questions/50657473
复制相似问题