【问题标题】:How to solve Java compiler-error "cannot find symbol"? [closed]如何解决 Java 编译器错误“找不到符号”? [关闭]
【发布时间】:2021-10-01 00:45:03
【问题描述】:

我刚刚开始学习如何用 Java 编写代码。

任务

我在网上平台replit做了一个小程序。 程序比较两个ints:

  • 它们是否相等
  • 哪个大,哪个小

错误

我在编译时偶然发现了这些错误:

Main.java:22: error: cannot find symbol
   System.out.println("El mayor es " + may);
                                       ^
 symbol:   variable may
 location: class Main

Main.java:23: error: cannot find symbol
   System.out.println("El menor es " + men);
                                       ^
 symbol:   variable men
 location: class Main

2 errors

我的代码

class Main {
  public static void main(String[] args) {
    int a = 5;
    int b = 6;
    if (b==a)
    {
      System.out.println("Both digits are equivalent");
    }
    else 
    {
      if (b>a)
      {
        int may = b;//may stands for the position of the greater number
        int men = a;//men stands for the position of the smaller number
      }
      else 
      {
        int may = a;
        int men = b;
      }
      System.out.println("the bigger number is " + may);
      System.out.println("the smaller number is " + men);
    }
  }
}

【问题讨论】:

  • 我编辑了问题以使问题清晰且可重现。我可以阅读以下问题:“如何解决 Java 编译器错误...”。请按要求填写research for [java] cannot find symbol on Stackoverflow,您会找到答案。因为这种编译器错误“找不到符号”对于 Java 新手来说很常见。
  • 感谢编辑,我对这门语言还很陌生,所以我真的不知道如何命名它。

标签: java variables compiler-errors


【解决方案1】:

maymen 不在您最后两个打印语句的范围内。有不同的解决方案。其中之一是在if 语句之外声明变量。 EDIT TO SHOW DECLARATION:我已经有一段时间没有写过java了,但我相信声明是这样的:

...
else
{
  int may;
  int men;
  if (b>a)
  {
     may = b;
     men = a;
  }
  else
  {
     may = a;
     men = b;
  }
// print statements

【讨论】:

  • 问题是我不能把它们放在 if 语句之外,因为那是构成代码的主要函数,或者至少我不知道如何编写外部变量的 def if 语句。如果您有其他解决方案,那将非常有帮助,谢谢。
  • 编辑了我的答案以显示if 声明之外的声明。请试一试,如果可行,请告诉我。
  • 编程和 Java 的新手可能想知道“范围”这个术语。所以他们可能不明白“符号”或变量“在范围内”或“在范围外”意味着什么。你能解释清楚吗?
  • 术语“declare”(创建)、“assign”(写入)或“reference”(读取)之间的区别可能解释了在何处引入以及在何处使用变量(范围、代码中的位置) .
  • 感谢您的回答和解释。结果很好,我终于可以完成作业了:)
猜你喜欢
  • 1970-01-01
  • 2014-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-19
  • 2014-07-01
  • 1970-01-01
相关资源
最近更新 更多