繁体   English   中英

Java 变量不在 scope 中,即使我已经在 class 中声明了它?

[英]Java variable is out of scope even though I've already declared it in the class?

我的编译器一直说我的 toString 方法中的“美分”超出了 scope,但我不明白为什么这是因为我已经在 class 中声明了它。

这是我的代码:

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;
}

}

由于您想要两个精度(即 %.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);
    }

Output:美分:34 美元 12.34 美元

您在方法中声明了 cents,因此它具有函数范围。 您需要像使用 value 一样在 class 级别上声明它。

private Double value;
private int cents;

在您的方法中,您可以这样称呼它:

cents = (int)(value * 100) % 100;

这将解决您的技术问题。 有些人会说这是不对的,因为您是直接从价值计算美分。 别人会说没问题。 最后,这取决于您计算 function 的频率。 在某些情况下,最好将它放在一个额外的变量中。

更改如上所示的代码将解决您要求的技术问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM