有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java局部变量gcd可能尚未初始化

我有以下代码,其中变量gcd在gcd()函数中,这显示了错误:

The local variable gcd may not have been initialized.

代码是:

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;

    }
}

为什么要初始化gcd


共 (2) 个答案

  1. # 1 楼答案

    • 首先,每个变量在使用前都必须进行初始化
    • 编译器这样做是为了确保在执行或使用程序中的变量时,变量中至少有一个值
    • 以避免编译时错误使用此选项
    • 在您的情况下,如果值n1n2为0,则控件将不会进入for循环,并且将不会初始化gcd。返回gcd值时,将出现编译时错误
    • 我还想指出java文档中的这一部分

      Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable. If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.

      你可以在this链接中获得完整的文档

      Credit-SO Question

      也就是说,因为gcd是一个局部变量,所以它没有用默认值初始化

    • 因此,必须初始化变量

    • 这就是你应该做的-

      public static int gcd(int n1, int n2) {
      int gcd = 0;
      for (int n = 1; n <= n1 && n <= n2 ; n++) {
      if (n1 % n == 0 && n2 % n == 0)
           gcd = n;
      }
      return gcd;
      
      }
      

      int gcd = 0;

    希望这个答案对你有帮助

  2. # 2 楼答案

    因为{cd1}本质上是需要声明的

    你的方法声明了int gcd,但除了在if语句中之外,从不给它赋值。有一种可能的情况是,if语句永远不会被输入,因为其中的布尔语句永远不会计算为true。在这种可能的情况下,会有一个问题,因为return gcd;会执行,即使没有给它赋值。Java不希望发生这种情况,并警告您

    您可能需要设置一个默认值,以防它找不到gcd。这个值显然是1,所以声明为:int gcd = 1;