2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Java】釣り銭を計算する方法

Posted at

はじめに

本記事では、Java言語を使用して釣り銭を計算する方法について学習したのでアウトプットします。釣り銭計算は、支払い金額と預り金額を入力し、各種紙幣や硬貨の枚数を計算するプログラムです。具体的なコード例を交えて解説します。

釣り銭計算の実装

以下に、釣り銭を計算するJavaプログラムのコードを示します。

public class Task {
    public static void main(String[] args) {
        // 数値リテラルはアンダースコアを入れて桁の可読性をよくすることが出来る
        int deposit = 10_000; // 10000 と同等
        int amount = 3_214; // 合計金額
        int Change = deposit - amount; //おつり

        // 以下に処理を追加する
        System.out.print("合計金額:" + String.format("%,d",amount) + "円 ");
        System.out.print("預り金" + String.format("%,d", deposit) + "円 ");
        System.out.println("おつり" + String.format("%,d", Change) + "円");

        int[] bills = { 5000, 1000 }; // 確認したいお札の種類を配列に組み込む
        int[] coins = { 500, 100, 50, 10 }; // 確認したい硬貨の種類を配列に組み込む

        // 紙幣の枚数を計算して出力する
        // 金額が高い順から割り切れた額があれば合計金額から減算処理を行う
        for (int bill : bills) {
            int count = Change / bill; // データ形式がintなので整数の値のみ代入される
            System.out.println(String.format("%,d", bill) + "円札:" + count + "枚");
            Change %= bill; // 金額を割り算して余った金額が次の計算に使用される
        }

        for (int coin : coins) {
            int count = Change / coin;
            System.out.println(String.format("%,d", coin) + "円玉:" + count + "枚");
            Change %= coin; // 最終的に1円で全て割り切れる計算なのでChangeが0になったら終了となる
        }
    }
}

実行結果

実行結果
合計金額:3,214 預り金:10,000 おつり:6,786
5,000円札:1
1,000円札:1
500円玉:1
100円玉:2
50円玉:1
10円玉:3
1円玉:6

まとめ

本記事では、Javaを使用して釣り銭を計算する方法を解説しました。何かの参考になれば幸いです

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?