所以,这是我的类,其中包含我的构造函数和访问器方法:
image_name tags
0 img1 yes
1 img2 no
2 img3 yes
3 img4 no
代码可能很草率,因为我一直在四处寻找解决此错误的方法,但是这是我要运行的驱动程序。尝试从另一个类的访问器方法调用我的值时发生错误。
public class sac
{
// Initializing instance variables.
private double bal;
private double[] dep;
private double[] wit;
/**
* Constructor for objects of class sac
*/
public sac()
{
//Declaring instance variables
bal = 500;
//Deposits:
double[] dep = new double[5];
dep[0] = 100.00;
dep[1] = 124.00;
dep[2] = 78.92;
dep[3] = 37.55;
dep[4] = 83.47;
//Withdrawals:
double[] wit = new double[7];
wit[0] = 29.88;
wit[1] = 110.00;
wit[2] = 27.52;
wit[3] = 50.00;
wit[4] = 12.90;
wit[5] = 15.20;
wit[6] = 11.09;
}
/**
* Returns and sets the value of balance.
*
*
* @return bal
*/
public double setBal(double b)
{
//Declaring instance variables
b = bal;
return bal;
}
/**
* Returns and sets the values of deposits.
*
*
* @return deposits
*/
public double[] getDep()
{
double[] d = new double[5];
//Deposits:
d[0] = dep[0];
d[1] = dep[1];
d[2] = dep[2];
d[3] = dep[3];
d[4] = dep[4];
return d;
}
/**
* Returns and sets the values of withdrawals.
*
*
* @return withdrawals
*/
public double[] getWit()
{
double[] w = new double[7];
//Withdrawals:
w[0] = wit[0];
w[1] = wit[1];
w[2] = wit[2];
w[3] = wit[3];
w[4] = wit[4];
w[5] = wit[5];
w[6] = wit[6];
return w;
}
}
答案 0 :(得分:0)
您的setBal函数是错误的伙伴。
public double setBal(double b)
{
// Declaring instance variables
// b = bal; <--- wrong
bal = b; // <--- right
return bal;
}
答案 1 :(得分:0)
在sacDemo类中,您正在初始化新的数组对象,并将它们分配给变量d和w。
double[] dep = new double[5];;// {0.0 , 0.0 , 0.0 , 0.0 , 0.0 }
double[] wit = new double[7];// {0.0 , 0.0 , 0.0 , 0.0 , 0.0 , 0.0 , 0.0 }
double[] d = dep; // {0.0 , 0.0 , 0.0 , 0.0 , 0.0 }
double[] w = wit; // {0.0 , 0.0 , 0.0 , 0.0 , 0.0 , 0.0 , 0.0 }
因此,在此行之后,“ d”和“ w”将具有初始化为0.0的元素。 在java中,=(assignment)运算符从右到左起作用。您在'dep'中拥有的内容将分配给'd',因此迭代d和w将得到具有0.0值的元素。
w = sac.getWit();
d = sac.getDep();
此后,您可以使用'w'和'd'而不是'dep'和'wit'访问值,因为它们仍然引用先前的数组。
因此,当您进行迭代时,请改用下面的代码片段
for(int i=0;i<5;i++){
System.out.println(d[i]);
}
for(int i=0;i<6;i++){
System.out.println(w[i]);
}
希望这对您有帮助!