簡體   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