创建硬币计算

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

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

  1. int money;
  2. int denom;
  3. Scanner sc=new Scanner(System.in);
  4. System.out.println("Please enter the amount of coins you have in penny value");
  5. money = sc.nextInt();
  6. System.out.println("Also the denomiation you would like exclude; 2, 1, 50p, 20p, 10p");
  7. denom = sc.nextInt();
  8. while (money > 0){
  9. if (money >= 200) {
  10. System.out.println("£2");
  11. money -= 200;
  12. }
  13. else if (money >= 100) {
  14. System.out.println("£1");
  15. money -= 100;
  16. }
  17. else if (money >= 50) {
  18. System.out.println("50p");
  19. money -= 50;
  20. }
  21. else if (money >= 20) {
  22. System.out.println("20p");
  23. money -= 20;
  24. }
  25. else if (money >= 10) {
  26. System.out.println("10p");
  27. money -= 10;
  28. }
  29. else if (money >= 1) {
  30. System.out.println("1p");
  31. money -= 1;
  32. }
vzgqcmou

vzgqcmou1#

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

  1. int money;
  2. int denom;
  3. Scanner sc=new Scanner(System.in);
  4. System.out.println("Please enter the amount of coins you have in penny value");
  5. money = sc.nextInt();
  6. System.out.println("Also the denomiation you would like exclude; 2, 1, 50p, 20p, 10p");
  7. String input = sc.next(); //saving user input as a string
  8. if (input.contains("p"))
  9. { //converting string to int by removing the p
  10. denom = Integer.parseInt(input.substring(0, input.indexOf("p")));
  11. }
  12. else
  13. { //if there's no p, multiply its value by 100
  14. denom = Integer.parseInt(input) * 100;
  15. }
  16. while (money > 0){
  17. if (money >= 200 && denom != 200) {
  18. System.out.println("£2");
  19. money -= 200;
  20. }
  21. else if (money >= 100 && denom != 100) {
  22. System.out.println("£1");
  23. money -= 100;
  24. }
  25. else if (money >= 50 && denom != 50) {
  26. System.out.println("50p");
  27. money -= 50;
  28. }
  29. else if (money >= 20 && denom != 20) {
  30. System.out.println("20p");
  31. money -= 20;
  32. }
  33. else if (money >= 10 && denom != 10) {
  34. System.out.println("10p");
  35. money -= 10;
  36. }
  37. else if (money >= 1) {
  38. System.out.println("1p");
  39. money -= 1;
  40. }
  41. }
展开查看全部

相关问题