java 我一直在第32行遇到“找不到符号错误”

9rygscc1  于 2023-04-04  发布在  Java
关注(0)|答案(3)|浏览(178)
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;
    }
    for (int LCP = LCM; LCP <= 100000000; LCP++) {
      if ((LCP % number1 == 0) && (LCP % number2 == 0)) {
        int temp = LCP;
      }

    }
    return temp;
  }

}

我认为我正确地定义了返回变量。我知道这是一个小问题,但我不能指出错误或调整,我必须作出。

bmp9r5qi

bmp9r5qi1#

你在if condition中的for loop中定义了变量temp。它不存在于这个作用域之外,这意味着一旦if条件结束,变量就不再存在。所以当你试图在return temp中使用它时,程序不知道你在引用什么。
要解决这个问题,您只需要在整个函数的作用域中定义temp,类似于您定义int LCM = 0;的方式,然后在if条件中赋值。
工作代码:

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;
    int temp;
    if (number1 > number2) {
      LCM = number1;
    } else {
      LCM = number2;
    }
    for (int LCP = LCM; LCP <= 100000000; LCP++) {
      if ((LCP % number1 == 0) && (LCP % number2 == 0)) {
        temp = LCP;
      }

    }
    return temp;
  }

}

您可以阅读更多关于scopes here

9rnv2umw

9rnv2umw2#

在循环函数外定义temp,一旦找到所需的值,您可能希望中断执行:

public static int lcm(int number1, int number2) {
    int LCM = 0;
    int temp = 0; 
    if (number1 > number2) {
      LCM = number1;
    } else {
      LCM = number2;
    }
    for (int LCP = LCM; LCP <= 100000000; LCP++) {
      if ((LCP % number1 == 0) && (LCP % number2 == 0)) {
        temp = LCP;
        break; // Finish loop 
      }

    }
    return temp;
  }
fzsnzjdm

fzsnzjdm3#

你已经在if语句中定义了'temp'变量。所以,它已经成为一个局部变量。局部变量不能在定义它们的条件或函数之外访问。所以,你需要在if语句之外定义'temp'变量。修改的代码:

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;
    int temp = 0;
    if (number1 > number2) {
      LCM = number1;
    } else {
      LCM = number2;
    }
    for (int LCP = LCM; LCP <= 100000000; LCP++) {
      if ((LCP % number1 == 0) && (LCP % number2 == 0)) {
          temp = LCP;
      }

    }
    return temp;
  }

}

相关问题