Java:“错误:找不到符号”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20137581/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 23:25:39  来源:igfitidea点击:

Java: "error: cannot find symbol"

javavariablessymbols

提问by Skelatox

(Rookie mistake, I'm sure.)

(菜鸟错误,我敢肯定。)

I'm a first year computer science student, and attempting to write a program for an assignment, with the code;

我是计算机科学专业的一年级学生,正在尝试使用代码为作业编写程序;

import java.util.Scanner;
public class Lab10Ex1 {

   public static void main(String[] arg) {

    Scanner keyboard = new Scanner(System.in);
    System.out.println("Please type a number: ");
    int n = keyboard.nextInt(); 
    calcNumFactors();
  }
  public static void calcNumFactors(){

   System.out.print(n + 1);

  }

}

But upon compiling, I get the error;

但是在编译时,我得到了错误;

Lab10Ex1.java:10: error: cannot find symbol System.out.print(n + 1); ^

symbol: variable n

location: class Lab10Ex1

Lab10Ex1.java:10: 错误:找不到符号 System.out.print(n + 1); ^

符号:变量 n

地点:Class Lab10Ex1

If someone could explain to me what I've done wrong, or how to fix it, I would greatly appreciate it.

如果有人可以向我解释我做错了什么,或者如何解决它,我将不胜感激。

采纳答案by Hovercraft Full Of Eels

The nvariable was declared in the mainmethod and thus is visible only in the main method, nowhere else, and certainly not inside of the calcNumFactorsmethod. To solve this, give your calcNumFactorsmethod an intparameter which would allow calling methods to pass an int, such as ninto the method.

n变量是在main方法中声明的,因此仅在主方法中可见,在其他任何地方都不可见,当然也不在calcNumFactors方法内部。要解决此问题,请为您的calcNumFactors方法提供一个int参数,该参数将允许调用方法将int,例如传递n到方法中。

public static void calcNumFactors(int number) {
   // work with number in here
}

and call it like so:

并像这样称呼它:

int n = keyboard.nextInt(); 
calcNumFactors(n);

回答by Lingasamy Sakthivel

You must declare the variable nin public static void calcNumFactors()

您必须npublic static void calcNumFactors()

In your code, you have to pass the value of n as an argument to the function calcNumFactors()as Hovercraft Full Of Eels said.

在您的代码中,您必须将 n 的值作为参数传递给函数,calcNumFactors()如 Hovercraft Full Of Eels 所说。

回答by ricky

import java.util.Scanner;
public class Lab10Ex1 {

   private static int n;

   public static void main(String[] arg) {
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Please type a number: ");
     n = keyboard.nextInt(); 
    calcNumFactors();
  }
  public static void calcNumFactors(){

   System.out.print(n + 1);

  }
}