【问题标题】:Java variable is out of scope even though I've already declared it in the class?Java 变量超出范围,即使我已经在类中声明了它?
【发布时间】: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 代替,大小写很重要)。

标签: java variables


【解决方案1】:

因为你想要两个精度(即 %.2f 中的格式值)作为值,你可以考虑使用类似下面的东西

 // Returns a String representation in the format  $12.34
    public String toString()
    {
    return "$" + String.format("%.2f", value) ;
    }

    // main class

    public static void main(String[] a)
    {
        Currency c = new Currency(12.3423456d);
        System.out.println("Cents: "+c.getCents());

        System.out.println(c);
    }

输出: 美分:34 $12.34

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-19
    • 1970-01-01
    • 2016-01-14
    • 2020-02-03
    • 2012-06-11
    • 2019-11-15
    • 2021-04-28
    • 1970-01-01
    相关资源
    最近更新 更多