Java代码第32行报cannot find symbol error,求排查修复
解决Java LCM代码中的"cannot find symbol error"错误
你碰到的这个编译错误,核心原因是变量作用域的问题:temp变量是在if语句的大括号内部定义的,它的有效范围只限于这个if块里,当你在方法最后写return temp;时,编译器根本找不到这个变量,所以报错。
另外你的代码还有个小问题:找到符合条件的公倍数后没有跳出循环,会一直遍历到100000000,完全没必要。
修正后的代码如下:
import java.util.Scanner; class Source { public static void main(String[] args) { Scanner scan = new Scanner(System.in); // Enter the two numbers in the input console int number1 = scan.nextInt(); int number2 = scan.nextInt(); System.out.print(lcm(number1, number2)); } public static int lcm(int number1, int number2) { int LCM = 0; if (number1 > number2) { LCM = number1; } else { LCM = number2; } int temp = 0; // 把temp移到循环外定义,扩大作用域 for (int LCP = LCM; LCP <= 100000000; LCP++) { if ((LCP % number1 == 0) && (LCP % number2 == 0)) { temp = LCP; break; // 找到最小公倍数后立即跳出循环 } } return temp; } }
关键修正点:
- 将
temp变量的定义移到for循环之前,让它的作用域覆盖整个lcm方法,这样return语句就能正常访问 - 找到符合条件的最小公倍数后,用
break终止循环,避免无效遍历,提升代码效率
内容的提问来源于stack exchange,提问作者happyashbunny
相关产品推荐
相关产品推荐

