当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Small code, value isn't carried

问题描述:

I've got this problem, I have a java file that obtains 2 variables from another file and is supposed to add them together and return the summed value. So far it works on obtaining the values aFirst and aSecond but I'm not sure why value one and two is lost (is back at 0) when it gets to the sum method. This is for an assignment I have for homework.

public class Pair

{

private double one, two ;

public Pair(double aFirst, double aSecond)

{

double one = aFirst;

double two = aSecond;

}

public double sum()

{

double xys = one + two;

return(xys);

}

}

网友答案:

You're declaring one and two as local variables, shadowing the instance variables.

网友答案:

the problem is the constructor. you are creating local variables and not using the class fields

private double one, two ;
public Pair(double aFirst, double aSecond)
{
    this.one = aFirst;
    this.two = aSecond;
}

you can do it without the "this." but dont put type ahead

网友答案:

Use this to access the class member variables in override cases when you have the same variable name in local scope and in the class members.

分享给朋友:
您可能感兴趣的文章:
随机阅读: