[英]Java variable is out of scope even though I've already declared it in the class?
My compiler keeps saying that 'cents' in my toString method is out of scope, but I don't understand why this is because I've already declared it in the class.我的编译器一直说我的 toString 方法中的“美分”超出了 scope,但我不明白为什么这是因为我已经在 class 中声明了它。
Here is my code:这是我的代码:
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;
}
} }
as you want two precision(ie format value in %.2f) for value you can consider using something like below由于您想要两个精度(即 %.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: Cents: 34 $12.34 Output:美分:34 美元 12.34 美元
You declared cents inside a method, so it has function-scope.您在方法中声明了 cents,因此它具有函数范围。 You need to declare it on class level like you did with value.
您需要像使用 value 一样在 class 级别上声明它。
private Double value;
private int cents;
In your method you can call it like this:在您的方法中,您可以这样称呼它:
cents = (int)(value * 100) % 100;
That would solve your technical problem.这将解决您的技术问题。 Some people would say that's not right because you are calculating cents directly from value.
有些人会说这是不对的,因为您是直接从价值计算美分。 Others will say it's fine.
别人会说没问题。 In the end it depends how often you are calling the function if you calculate it.
最后,这取决于您计算 function 的频率。 In some cases it will be better to have it in an extra variable.
在某些情况下,最好将它放在一个额外的变量中。
Changing the code like shown above will solve the technical problem you asked for.更改如上所示的代码将解决您要求的技术问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.