Java正在给我这个错误。我已经工作了一段时间,我很难过。我无法弄清楚为什么java找不到总和?提前致谢。 :
C:\Users\Keegan\Documents\TwoNumbers.java:70: error: cannot find symbol
System.out.println( sum );
^
symbol: variable sum
location: class TwoNumbers
1 error
以下是代码:
public class TwoNumbers {
/*** Class Constants ***/
private final double DEFAULT_NUMBER1 = 10;
private final double DEFAULT_NUMBER2 = 15;
/*** Class Variables -- State of the object ***/
private double number1;
private double number2;
/*** Constructor Methods -- Set the state of the object double n1, double n2***/
public TwoNumbers () {
number1 = DEFAULT_NUMBER1;
number2 = DEFAULT_NUMBER2;
}
public void setNumbers ( double n1, double n2 ) {
this.number1=n1;
this.number2=n2;
}
/*** Accessor methods ***/
public double getNumber1() {
return number1;
}
public double getNumber2() {
return number2;
}
public double sum(double n1, double n2) {
double sum;
sum = n1 + n2;
return sum;
}
/*** Transformer/Mutator Methods ***/
public static void main( String args[] ) {
System.out.println( sum );
System.out.println("" );
System.out.println("" );
System.out.println("" );
System.out.println("" );
System.out.println("" );
System.out.println("" );
}
}
答案 0 :(得分:3)
sum
被定义为sum
方法中的局部变量,它没有此方法的上下文(或无法访问)......
public double sum(double n1, double n2) {
double sum;
根据您的代码尝试执行的操作,您不应该尝试以任何方式访问它,而应该只是使用TwoNumbers
的实例来打印结果...
System.out.println(new TwoNumbers().sum(1, 1));
例如......
答案 1 :(得分:2)
因为变量sum的范围仅在您声明它的方法中可见。
您无法访问仅对您未调用的方法本地的变量。
public double sum(double n1, double n2) {
double sum;
sum = n1 + n2;
return sum;
} // sum is no longer visible to anything else
// the variable was used and garbage collected within the sum() method.
答案 2 :(得分:1)
变量“sum”被定义为方法“sum”中的局部变量。在发生错误的“main()”函数中,唯一可见的名称“sum”是成员函数。要调用它,您需要创建一个实例,并使用带有这样的参数的括号:
public static void main(String args[]) {
TwoNumbers instance = new TwoNumbers();
System.out.println(instance.sum(1, 2)); // prints 3
System.out.println("" );
System.out.println("" );
System.out.println("" );
System.out.println("" );
System.out.println("" );
System.out.println("" );
}