我在运行此代码时出现问题。
import java.io.*;
public class divisi {
public int findGCD(int a, int b) {
int c, d;
int div;
if(a>b) {
c = a;
} else {
c = b;
}
for(d = 1 ; d <= c; d++) {
if(a%d == 0 && b%d == 0) {
div = d;
}
}
return div;
}
public static void main(String[]args)throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter two numbers:");
int a1 = Integer.parseInt(br.readLine());
int b1 = Integer.parseInt(br.readLine());
divisi obj2 = new divisi();
int m = obj2.findGCD(a1 , b1);
System.out.println("The GCD or HCF of the entered numbers is " + m);
}
}
我收到的错误是变量div未初始化,即使在for循环中它已被初始化(div = d)。谁能告诉我,我做错了什么?
答案 0 :(得分:0)
对于a <= 0
和b <=0
,您永远不会初始化div
。
只需通过div
初始化0
来修复它。