проблема с Java упражнением метода обертки - PullRequest
0 голосов
/ 27 апреля 2020

В настоящее время я работаю над упражнением для своего класса 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());
    }
}

Ответы [ 3 ]

0 голосов
/ 27 апреля 2020

Прежде всего, у вас есть ненужный бокс / распаковка. Либо назначьте непосредственно локальной переменной Integer-values, чем надеяться на автоматическую распаковку только для автоматической установки значения сразу ...

   res = Integer.valueOf(s);

, либо просто верните значение сразу ...

   return( Integer.valueOf(s) );

или используйте другой метод Integer, который преобразует String в примитив int ...

   r = Integer.parseInt(s);
   res = new Integer(r);

Но закрытый Double, вероятно, плохой выбор для класса Currency, особенно когда вы Выставляешь публичные c доллары и центы как целые числа. Лучший выбор включает (примитив) long или int числа центов или BigDecimal.

0 голосов
/ 27 апреля 2020

Я нашел решение своей проблемы! Благодаря помощи многих, прежде всего @ggr, я смог найти решение. У CodeHs, похоже, есть ошибочная проблема с контрольным примером, которую я просто обошел с помощью оператора if.

a MASSIVE спасибо всем, кто прокомментировал, все это было очень полезно, и я ценю это очень много!

ниже - окончательный, рабочий код для класса 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()
    {
        Integer res = 0;
        if((int)(100*(value - this.getDollars())) == (80-1)){
            res = (int)(100*(value - this.getDollars())) + 1;
        }
        else{
            res = (int)(100*(value - this.getDollars()));
        }
        return res;
    }

    // Returns a String representation
    // in the format
    // $12.34
    public String toString()
    {
        return ("$" + this.getDollars() + "." + this.getCents());
    }
}
0 голосов
/ 27 апреля 2020

Может быть, вы пытаетесь с такими значениями, как 46465.12 (ie не 2 цифры. 2 2 цифры)

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

    public static 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, s.indexOf('.'));
            return Integer.valueOf(s);
        }

        // 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(s.indexOf('.') + 1);
            //System.out.println(s);
            return Integer.valueOf(s); //Problem Line
        }

        // Returns a String representation
        // in the format
        // $12.34
        public String toString() {
            return ("$" + value);
        }
    }

}
...