【发布时间】:2019-11-05 23:54:23
【问题描述】:
我的编译器一直说我的 toString 方法中的 'cents' 超出范围,但我不明白为什么会这样,因为我已经在类中声明了它。
这是我的代码:
public class Currency
{
private Double value;
// Constructor
public Currency(Double startValue)
{
value = startValue;
}
// Sets value to newValue
public void setValue(Double newValue)
{
value = newValue;
}
// Returns the dollar portion of value
// if value is 12.34, returns 12
public Integer getDollars()
{
return value.intValue();
}
// Returns the cents portion of value
// as an Integer
// if value is 12.34, returns 34
public Integer getCents()
{
Integer cents = (int)(value * 100) % 100;
return cents;
}
// Returns a String representation
// in the format
// $12.34
public String toString()
{
return "$" + value + cents;
}
}
【问题讨论】:
-
不,你没有
cents只存在于方法getCents -
cents是您的getCents方法中的局部变量。 -
return "$" + getDollars() + "." + getCents();将是实现toString()的更好方法。 -
" ... 因为我已经在类中声明了它" - 实际上,您在方法中声明了它。因此它是一个 local 变量,并且超出了 other 方法的范围。
-
请注意,Java 没有隐式属性:即使您创建了
get方法并不意味着您可以通过键入cents来访问它(并且,如果一个属性已创建,您可能会期望Cents代替,大小写很重要)。