2016-02-01 127 views
0

我有我的代碼,用戶輸入金額和輸出顯示的數量二十,十,五,一,四分之一,硬幣,鎳和便士,我想用戶輸入一定數量的硬幣(例如36),並獲得只有硬幣,這使得36美分。這意味着我應該得到1個季度,1個角錢和1個pennie。請有人幫我解決這個問題。非常感謝!如何獲得Java中的硬幣數量?

注:
DecimalFormat的類時並不需要

這裏是我的代碼:

import java.util.Scanner; 
import java.text.DecimalFormat; 
public class Compu 
{ 
public static void main(String[] args) 
{ 
    Scanner input = new Scanner(System.in); 
    DecimalFormat decimalFormat = new DecimalFormat("0.00"); 

    System.out.println("Please Enter an amount of Money:");  
    double change = input.nextDouble(); 


    int dollars = (int)change; 
    int twenties = dollars/20; 
    int dollars1 = dollars % 20; 
    int tens = dollars1/10; 
    int dollars2 = dollars % 10; 
    int fives = dollars2/5; 
    int dollars3 = dollars % 5; 
    int ones = dollars3; 

    String moneyString = decimalFormat.format(change); 
    String changeString = Double.toString(change); 
    String[] parts = moneyString.split("\\."); 
    String part2 = parts[1]; 
    double cents5 = Double.parseDouble(part2); 

    int cents = (int)cents5; 
    int quarters = cents/25; 
    int cents1 = cents % 25; 
    int dimes = cents1/10; 
    int cents2 = cents % 10; 
    int nickels = cents2/5; 
    int cents3 = cents % 5; 
    int pennies = cents3; 

    System.out.println("Input entered by user: " + "$" + moneyString); 


    System.out.println(twenties + " Twenties"); 
    System.out.println(tens + " Tens"); 
    System.out.println(fives + " Fives"); 
    System.out.println(ones + " Ones"); 
    System.out.println(quarters + " Quarters"); 
    System.out.println(dimes + " Dimes"); 
    System.out.println(nickels + " Nickels"); 
    System.out.println(pennies + " Pennies"); 

    } 
} 
+0

它是如何比進入'0.36'到你的程序有什麼不同? –

+0

@ PM77-1,我不想輸入0.36。我只想輸入36 – HenryDev

回答

1

模運算符是你的朋友:

public static void main(String[] args) { 
    Scanner input = new Scanner(System.in); 
    System.out.println("Please enter amount in cents"); 
    double cents = input.nextInt(); 

    int numQuarters = cents/25; 
    int numDimes = (cents % 25)/10; 
    int numNickels = ((cents % 25) % 10)/5; 
    int numPennies = ((cents % 25) % 10) % 5; 

    System.out.println(quarters + " Quarters"); 
    System.out.println(dimes + " Dimes"); 
    System.out.println(nickels + " Nickels"); 
    System.out.println(pennies + " Pennies"); 
} 
+0

如果我還想要鎳的數量呢? – HenryDev

+0

謝謝你的幫助! – HenryDev

1

要做到這一點,完全刪除該計劃的一部分處理美元,並將用戶輸入直接提供給'cent S'。

而且,這一部分:(在少數情況下並非所有)

int cents = (int)cents5; 
int quarters = cents/25; 
int cents1 = cents % 25; 
int dimes = cents1/10; 
int cents2 = cents % 10; 
int nickels = cents2/5; 
int cents3 = cents % 5; 
int pennies = cents3; 

將是不精確的,因爲你是不改變的「仙」的值。因此,如果您輸入'36',它將返回1個季度(25),1個硬幣(35),1個鎳(40)和1個便士(41)。

爲了避免這種情況,使用下面的代碼:

int cents = (int)cents5; 
int quarters = cents/25; 
int cents1 = cents % 25; 
int dimes = cents1/10; 
int cents2 = cents1 % 10; 
int nickels = cents2/5; 
int cents3 = cents2 % 5; 
int pennies = cents3; 
+0

感謝您的提示! – HenryDev