2016-07-07 3 views
2

Я - noob для Java, и я пытаюсь написать программу, которая дает сумму изменений с учетом двух долларовых входов. Я не могу понять, что происходит. У меня особенно возникают проблемы с выпуском чеканки. Так, например, если человек задолжал 654,32 доллара и заплатил 987 долларов, их изменение должно составлять 332,68 доллара США, что составит 2 квартала, 1 копейка, 1 никель и 3 пинни.Вычисление суммы внесенного изменения

Любая помощь очень ценится!

import java.util.*; 
import java.math.*; 
import java.text.*; 


public class CorrectChange { 

    public static void main(String[] args) { 

     Scanner input = new Scanner(System.in); 

     BigDecimal AmtDue;  
     BigDecimal AmtPaid; 


     NumberFormat n = NumberFormat.getCurrencyInstance(Locale.US); 

     //User enters the amount that the customer owes 
     System.out.println("Enter the amount below that is due to be paid."); 
     System.out.print("$"); 
      AmtDue = input.nextBigDecimal(); 

      //Converts user's input into the currency format 
      AmtDue = AmtDue.setScale(2, BigDecimal.ROUND_HALF_UP); 
       double dAmtDue = AmtDue.doubleValue(); 
        String eAmtDue = n.format(dAmtDue); 

     //User enters the amount that the customer paid  
     System.out.println("Enter the amount below that has been paid."); 
     System.out.print("$"); 
      AmtPaid = input.nextBigDecimal(); 

      //Converts user's input into the currency format 
      AmtPaid = AmtPaid.setScale(2, BigDecimal.ROUND_HALF_UP); 
       double dAmtPaid = AmtPaid.doubleValue(); 
        String eAmtPaid = n.format(dAmtPaid); 

      //Checks to see if the amount paid is more than the amount owed 
      if (AmtDue.compareTo(AmtPaid)> 0){ 
       double dBal = AmtDue.subtract(AmtPaid).doubleValue(); 
       String eBal = n.format(dBal); 
       System.out.println("You still owe: " + eBal.toString()); 
      } 

      //Checks to see if the amount owed is more than the amount paid 
      if (AmtDue.compareTo(AmtPaid)< 0){ 
       int cBal = (AmtPaid.compareTo(AmtDue)*100); 
       double dBal = AmtPaid.subtract(AmtDue).doubleValue(); 
       String eBal = n.format(dBal); 


        int DolBills = (int) (dBal/1); 
        dBal = dBal % 1; 

        int quarters = (int) (dBal/25); 
        dBal = dBal % 25; 

        int dimes = (int) (cBal/10); 
        cBal = cBal % 10; 

        int nickles = (int) (cBal/5); 
        cBal = cBal % 5; 

        //pennies = (int) (dBal/100); 
        //dBal = dBal % 100; 

       System.out.println("You owe a balance of " + eAmtDue.toString() + ". Since you paid the amount of " + eAmtPaid.toString() + " your change is " + eBal.toString()); 
       System.out.println("Your change amount is as follows:\n" + 
        "\t" + DolBills + " $1 dollar bills \n" + 
        "\t" + quarters + " quarters \n" + 
        "\t" + dimes + " dimes \n" + 
        "\t" + nickles + " nickels \n"); 
        "\t" + numPennies + " pennies"; 

      } 

      //Checks to see if the amount paid is equal to the amount owed 
      if (AmtDue.compareTo(AmtPaid)== 0){ 
        System.out.println("Your balance has been paid. Thank you for your business."); 
      } 


    } 
+0

Используйте отладчик, чтобы узнать, что случилось. – Jens

+0

Вы показали нам свой ожидаемый результат, но каков ваш результат прямо сейчас, когда вы выполняете программу? –

ответ

1

Вы были почти там, вы немного перепутались с cBal и dBal. И преобразование изменений в их .XX значение.

Правильная версия ниже

import java.util.*; 
import java.math.*; 
import java.text.*; 


public class CorrectChange { 

    public static void main(String[] args) { 

     Scanner input = new Scanner(System.in); 

     BigDecimal AmtDue;  
     BigDecimal AmtPaid; 


     NumberFormat n = NumberFormat.getCurrencyInstance(Locale.US); 

     //User enters the amount that the customer owes 
     System.out.println("Enter the amount below that is due to be paid."); 
     System.out.print("$"); 
      AmtDue = input.nextBigDecimal(); 

      //Converts user's input into the currency format 
      AmtDue = AmtDue.setScale(2, BigDecimal.ROUND_HALF_UP); 
       double dAmtDue = AmtDue.doubleValue(); 
        String eAmtDue = n.format(dAmtDue); 

     //User enters the amount that the customer paid  
     System.out.println("Enter the amount below that has been paid."); 
     System.out.print("$"); 
      AmtPaid = input.nextBigDecimal(); 

      //Converts user's input into the currency format 
      AmtPaid = AmtPaid.setScale(2, BigDecimal.ROUND_HALF_UP); 
       double dAmtPaid = AmtPaid.doubleValue(); 
        String eAmtPaid = n.format(dAmtPaid); 

      //Checks to see if the amount paid is more than the amount owed 
      if (AmtDue.compareTo(AmtPaid)> 0){ 
       double dBal = AmtDue.subtract(AmtPaid).doubleValue(); 
       String eBal = n.format(dBal); 
       System.out.println("You still owe: " + eBal.toString()); 
      } 

      //Checks to see if the amount owed is more than the amount paid 
      if (AmtDue.compareTo(AmtPaid)< 0){ 
       double dBal = AmtPaid.subtract(AmtDue).doubleValue(); 
       String eBal = n.format(dBal); 


        int DolBills = (int) (dBal/1); 
        dBal = dBal % 1.0; 

        int quarters = (int) (dBal/.25); 
        dBal = dBal % .25; 

        int dimes = (int) (dBal/.10); 
        dBal = dBal % .10; 

        int nickles = (int) (dBal/.05); 
        dBal = dBal % .05; 

        int numPennies = (int) (dBal/.01); 
        //dBal = dBal % 0.01; 

       System.out.println("You owe a balance of " + eAmtDue.toString() + ". Since you paid the amount of " + eAmtPaid.toString() + " your change is " + eBal.toString()); 
       System.out.println("Your change amount is as follows:\n" + 
        "\t" + DolBills + " $1 dollar bills \n" + 
        "\t" + quarters + " quarters \n" + 
        "\t" + dimes + " dimes \n" + 
        "\t" + nickles + " nickels \n" + 
        "\t" + numPennies + " pennies"); 

      } 

      //Checks to see if the amount paid is equal to the amount owed 
      if (AmtDue.compareTo(AmtPaid)== 0){ 
        System.out.println("Your balance has been paid. Thank you for your business."); 
      } 

    } 
    } 

Вы должны обязательно прочитать на Java Naming и кодирования конвенций.

+0

Спасибо Yogesh_D. Ваше решение было именно тем, что мне нужно! Он работает отлично. Как я уже сказал, я очень новичок в Java и вообще программирую. Мне бы очень хотелось узнать, какие ошибки в названии и кодировании я совершил. – BWMustang13

+0

Несколько вещей с моей головы, AmtPaid - не хорошее имя переменной, должно быть amtPaid, еще один пример NumberFormat n. Также было бы разумно разделить метод на различные более мелкие методы. И вы, вероятно, можете оптимизировать количество переменных, используемых для хранения данных. Google немного о соглашениях Java, вы должны получить старый солнечный документ. –

+0

Еще раз спасибо Yogesh_D. После того, как вы упомянули об этом, я вернулся сегодня и понял, что вы говорите для AmtPaid и NumberFormat. Спасибо за помощь и совет. – BWMustang13

Смежные вопросы