创建硬币计算

ao218c7q  于 2021-07-11  发布在  Java
关注(0)|答案(1)|浏览(297)

我正在创建一个硬币计算器,它将硬币的价值分解为面值,但我希望这样做,以便用户可以选择排除硬币的面值,请参阅下面我的代码。我在这里碰到了一堵墙,正在努力想一个代码来允许这种情况发生,如果有人有一个指针,我会非常感激。我没有问题创建一个代码,用户可以选择其中包括面额。

int money;
        int denom;
        Scanner sc=new Scanner(System.in);
        System.out.println("Please enter the amount of coins you have in penny value");
        money = sc.nextInt();
        System.out.println("Also the denomiation you would like exclude; 2, 1, 50p, 20p, 10p");
        denom = sc.nextInt();
        while (money > 0){
            if (money >= 200) {
                System.out.println("£2");
                money -= 200;
            }
            else if (money >= 100) {
                System.out.println("£1");
                money -= 100;
            }
        else if (money >= 50) {
            System.out.println("50p");
            money -= 50;
            }
        else if (money >= 20) {
            System.out.println("20p");
            money -= 20;
            }
        else if (money >= 10) {
            System.out.println("10p");
            money -= 10;
        }       
        else if (money >= 1) {
            System.out.println("1p");
            money -= 1;

    }
vzgqcmou

vzgqcmou1#

我想说,这可能是最基本的方法来做它没有创建一个单独的方法。将denom设置为排除的值,然后在减法之前检查一个硬币是否等于denom可能会起作用,因为反正没有那么多硬币。

int money;
        int denom;
        Scanner sc=new Scanner(System.in);
        System.out.println("Please enter the amount of coins you have in penny value");
        money = sc.nextInt();
        System.out.println("Also the denomiation you would like exclude; 2, 1, 50p, 20p, 10p");
        String input = sc.next(); //saving user input as a string
        if (input.contains("p"))
        { //converting string to int by removing the p 
            denom = Integer.parseInt(input.substring(0, input.indexOf("p")));
        }
        else
        { //if there's no p, multiply its value by 100
            denom = Integer.parseInt(input) * 100;
        }

        while (money > 0){
            if (money >= 200 && denom != 200) {
                System.out.println("£2");
                money -= 200;
            }
            else if (money >= 100 && denom != 100) {
                System.out.println("£1");
                money -= 100;
            }
            else if (money >= 50 && denom != 50) {
                System.out.println("50p");
                money -= 50;
                }
            else if (money >= 20 && denom != 20) {
                System.out.println("20p");
                money -= 20;
                }
            else if (money >= 10 && denom != 10) {
                System.out.println("10p");
                money -= 10;
            }       
            else if (money >= 1) {
                System.out.println("1p");
                money -= 1;

            }
        }

相关问题