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
Java: "error: cannot find symbol"
提问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 n
variable was declared in the main
method and thus is visible only in the main method, nowhere else, and certainly not inside of the calcNumFactors
method. To solve this, give your calcNumFactors
method an int
parameter which would allow calling methods to pass an int
, such as n
into 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 n
in public static void calcNumFactors()
您必须n
在public 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);
}
}