В настоящее время я работаю над упражнением для своего класса Computer Science, но продолжаю сталкиваться с этой упрямой проблемой при запуске кода.
Я нашел способ математически найти getCents (), и он работает, но всякий раз, когда я добавляю число, в котором центы равны 80 (например, 115.80), getCents () возвращает «79» вместо «80». Я обновил код класса Currency с помощью своего текущего кода.
Ниже приведен код как основного выполняемого кода тестирования, так и класса 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();
return (Integer.valueOf(s.substring(0, s.indexOf('.'))));
}
// Returns the cents portion of value
// as an Integer
// if value is 12.34, returns 34
public Integer getCents()
{
return((int)(100*(value - this.getDollars())));
}
// Returns a String representation
// in the format
// $12.34
public String toString()
{
return ("$" + this.getDollars() + "." + this.getCents());
}
}