变量即使在循环中初始化也未初始化

时间:2017-12-01 02:10:09

标签: java

我在运行此代码时出现问题。

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)。谁能告诉我,我做错了什么?

1 个答案:

答案 0 :(得分:0)

对于a <= 0b <=0,您永远不会初始化div

只需通过div初始化0来修复它。