I have the following code where variable gcd
is inside the gcd() function and this is showing the error:
The local variable gcd may not have been initialized.
The code is:
import java.util.Scanner;
public class GreatestCommonDivisorMethod {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Enter two numbers");
Scanner input = new Scanner(System.in);
int num1 = input.nextInt();
int num2 = input.nextInt();
System.out.println("the gcd of the " + num1 + " and " + num2 + " is " + gcd(num1,num2));
}
public static int gcd(int n1, int n2) {
int gcd ;
for (int n = 1; n <= n1 && n <= n2 ; n++) {
if (n1 % n == 0 && n2 % n == 0)
gcd = n;
}
return gcd;
}
}
Why gcd
should be initialized?