我目前正在为我的计算机科学课做练习,但是当我尝试运行代码时,始终出现此顽固错误:
Currency.java:第35行:无法转换为指定的数字类型。
但是,我已经仔细检查了我的代码,但我看不到为什么会出现此错误。
任何帮助,我们将不胜感激!
下面是正在运行的主要代码和Currency类(包含问题行)的代码。
。
这里是测试Currency类的代码(正在运行的代码)
public class CurrencyTester
{
public static void main(String[] args)
{
Currency bankRoll = new Currency(12.45);
System.out.println("Value of bankroll: " + bankRoll);
System.out.println("Dollars: " + bankRoll.getDollars());
System.out.println("Cents: " + bankRoll.getCents());
bankRoll.setValue(20.56);
System.out.println("Value of bankroll: " + bankRoll);
System.out.println("Dollars: " + bankRoll.getDollars());
System.out.println("Cents: " + bankRoll.getCents());
bankRoll.setValue(67.78);
System.out.println("Value of bankroll: " + bankRoll);
System.out.println("Dollars: " + bankRoll.getDollars());
System.out.println("Cents: " + bankRoll.getCents());
}
}
这里是Currency类中的代码
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()
{
String s = value.toString();
s = s.substring(0,2);
Integer res = Integer.valueOf(s);
return res;
}
// Returns the cents portion of value
// as an Integer
// if value is 12.34, returns 34
public Integer getCents()
{
String s = value.toString();
s = s.substring(3,5);
//System.out.println(s);
int r = Integer.valueOf(s); //Problem Line
Integer res = r;
return res;
}
// Returns a String representation
// in the format
// $12.34
public String toString()
{
return ("$" + value);
}
}
[您可能正在尝试使用46465.12之类的值(即不是2digits。2 2digits]