关于下面问题特定的类创建问题。

huangapple go评论67阅读模式
英文:

Problem with class creation specific to the below problem

问题

以下是问题中需要翻译的内容:

"I have a problem in a Java coding problem, and I could use a little bit of help in understanding the thought process of a condition mentioned in the problem (highlighted below).

The goal of this question is to design a cash register program. Your register currently has the following notes/coins within it:

One Pence: .01
Two Pence: .02
Five Pence: .05
Ten Pence: .10
Twenty Pence: .20
Fifty Pence: .50
One Pound: 1
Two Pounds: 2
Five Pounds: 5
Ten Pounds: 10
Twenty Pounds: 20
Fifty Pounds: 50

The aim of the program is to calculate the change that has to be returned to the customer with the least number of coins/notes. Note that the expectation is to have an object-oriented solution - think about creating classes for better reusability.

Now there is a similar post for this question on this platform, but I want to know how to use classes in this problem instead of hardcoding the denominations? I would highly appreciate if anyone can shed some light on it! I have written the following code for this, any help on changing this according to the condition above will be appreciated:"

英文:

I have a problem in a Java coding problem, and I could use a little bit of help in understanding the thought process of a condition mentioned in the problem (highlighted below).

The goal of this question is to design a cash register program. Your register currently has the following notes/coins within it:

One Pence: .01
Two Pence: .02
Five Pence: .05
Ten Pence: .10
Twenty Pence: .20
Fifty Pence: .50
One Pound: 1
Two Pounds: 2
Five Pounds: 5
Ten Pounds: 10
Twenty Pounds: 20
Fifty Pounds: 50

The aim of the program is to calculate the change that has to be returned to the customer with the least number of coins/notes. Note that the expectation is to have an object-oriented solution - think about creating classes for better reusability.

Now there is a similar post for this question on this platform, but I want to know how to use classes in this problem instead of hardcoding the denominations? I would highly appreciate if anyone can shed some light on it! I have written the following code for this, any help on changing this according to the condition above will be appreciated:

    import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.io.*;

public class Main {
  /**
   * Iterate through each line of input.
   */
  public static void main(String[] args) throws IOException {
    InputStreamReader reader = new InputStreamReader(System.in);
    BufferedReader in = new BufferedReader(reader);

    try {
        double purchasePrice = Double.parseDouble(in.readLine());
        double cash = Double.parseDouble(in.readLine());
        Main.calculateChange(purchasePrice, cash);
    } catch (Exception e) {
        System.out.println(e);
    }
  }

  public static void calculateChange(double purchasePrice, double cash) {
    
    float cashBack = (float) (cash - purchasePrice);
    
    if (cashBack < 0) {
      System.out.println("ERROR");
      return ;
    }
    else if (cashBack == 0){
      System.out.println(0);
    }
    StringBuilder change = new StringBuilder();

        while (cashBack > 0.01) {
            if (cashBack >= 50.0) {
                change.append("Fifty Pounds");
                cashBack -= 50.0;
            } else if (cashBack >= 20.0) {
                change.append("Twenty Pounds");
                cashBack -= 20.0; 
            } else if (cashBack >= 10.0) {
                change.append("Ten Pounds");
                cashBack -= 10.0;
            } else if (cashBack >= 5.0) {
                change.append("Five Pounds");
                cashBack -= 5.0;
            } else if (cashBack >= 2.0) {
                change.append("Two Pounds");
                cashBack -= 2.0;
            } else if (cashBack >= 1.0) {
                change.append("One Pound");
                cashBack -= 1.0;
            } else if (cashBack >= 0.5) {
                change.append("Fifty Pence");
                cashBack -= 0.5;
            } else if (cashBack >= 0.20) {
                change.append("Twenty Pence");
                cashBack -= 0.20;
            } else if (cashBack >= 0.1) {
                change.append("Ten Pence");
                cashBack -= 0.1;
            } else if (cashBack >= 0.05) {
                change.append("Five Pence");
                cashBack -= 0.05;
            } else if (cashBack >= 0.02) {
                change.append("Two Pence");
                cashBack -= 0.02;
            } else {
                change.append("One Pence");
                cashBack -= 0.01;
            }
            change.append(", ");
        }
        change.setLength(change.length() - 2);

        System.out.println(change.toString());
    // Access your code here. Feel free to create other classes as required
  }

}

答案1

得分: 0

以下是您提供的内容的中文翻译部分:

Coin类:保存硬币的面值和名称。

public class Coin {

    double value;
    String name;

    public Coin(double value, String name) {
        this.value = value;
        this.name = name;
    }

    public double getValue() {
        return value;
    }

    public String getName() {
        return name;
    }
}

Cash Register类:按降序保存不同类型的硬币。

public class CashRegister {

    LinkedHashSet<Coin> coins = new LinkedHashSet<>();

    public String calculateChange(double purchasePrice, double cash) {

        double cashBack = cash - purchasePrice;

        if (cashBack < 0) {
            System.out.println("ERROR");
            return "";
        }

        StringBuilder change = new StringBuilder();

        while (cashBack > 0) {
            Iterator<Coin> iterator = coins.iterator();
            while (iterator.hasNext()) {
                Coin coin = iterator.next();
                int count = 0;
                while (cashBack >= coin.getValue()) {
                    count++;
                    cashBack -= coin.getValue();
                }
                if (count > 0) {
                    change.append(count).append(" " + coin.getName());
                    change.append("\n");
                }
            }
        }
        return change.toString();
    }

    public LinkedHashSet<Coin> init() {
        coins.add(new Coin(50, "Fifty Pound"));
        coins.add(new Coin(20, "Twenty Pound"));
        coins.add(new Coin(10, "Ten Pound"));
        coins.add(new Coin(5, "Five Pound"));
        coins.add(new Coin(2, "Two Pound"));
        coins.add(new Coin(1, "One Pound"));
        coins.add(new Coin(0.5, "Fifty Pence"));
        coins.add(new Coin(0.2, "Twenty Pence"));
        coins.add(new Coin(0.1, "Ten Pence"));
        coins.add(new Coin(0.05, "Five Pence"));
        coins.add(new Coin(0.02, "Two Pence"));
        coins.add(new Coin(0.01, "One Pence"));
        return coins;
    }
}

现金注册的实例化和调用以获取找零:

public static void main(String[] args) throws IOException {
        InputStreamReader reader = new InputStreamReader(System.in);
        BufferedReader in = new BufferedReader(reader);
        try {
            // 初始化现金注册。
            CashRegister cashRegister = new CashRegister();
            cashRegister.init();

            double purchasePrice = Double.parseDouble(in.readLine());
            double cash = Double.parseDouble(in.readLine());

            // 计算找零。
            String result = cashRegister.calculateChange(purchasePrice, cash);
            System.out.println(result);

        } catch (Exception e) {
            System.out.println(e);
        }
    }

可以通过_init()_方法向现金注册中添加任何硬币面额。您还可以添加许多其他功能到现金注册,例如:

  • 维护余额。
  • 支持动态添加新面额。
  • 支持动态删除面额。
英文:

Complete solution is here:

Coin class: Holds a coin value and its name.

public class Coin {
double value;
String name;
public Coin(double value, String name) {
this.value = value;
this.name = name;
}
public double getValue() {
return value;
}
public String getName() {
return name;
}
}

Cash Register class: This holds different types of coins in descending order.

public class CashRegister {
LinkedHashSet&lt;Coin&gt; coins = new LinkedHashSet&lt;&gt;();
public String calculateChange(double purchasePrice, double cash) {
double cashBack = cash - purchasePrice;
if (cashBack &lt; 0) {
System.out.println(&quot;ERROR&quot;);
return &quot;&quot;;
}
StringBuilder change = new StringBuilder();
while (cashBack &gt; 0) {
Iterator&lt;Coin&gt; iterator = coins.iterator();
while (iterator.hasNext()) {
Coin coin = iterator.next();
int count = 0;
while (cashBack &gt;= coin.getValue()) {
count++;
cashBack -= coin.getValue();
}
if (count &gt; 0) {
change.append(count).append(&quot; &quot; + coin.getName());
change.append(&quot;\n&quot;);
}
}
}
return change.toString();
}
public LinkedHashSet&lt;Coin&gt; init() {
coins.add(new Coin(50, &quot;Fifty Pound&quot;));
coins.add(new Coin(20, &quot;Twenty Pound&quot;));
coins.add(new Coin(10, &quot;Ten Pound&quot;));
coins.add(new Coin(5, &quot;Five Pound&quot;));
coins.add(new Coin(2, &quot;Two Pound&quot;));
coins.add(new Coin(1, &quot;One Pound&quot;));
coins.add(new Coin(0.5, &quot;Fifty Pence&quot;));
coins.add(new Coin(0.2, &quot;Twenty Pence&quot;));
coins.add(new Coin(0.1, &quot;Ten Pence&quot;));
coins.add(new Coin(0.05, &quot;Five Pence&quot;));
coins.add(new Coin(0.02, &quot;Two Pence&quot;));
coins.add(new Coin(0.01, &quot;One Pence&quot;));
return coins;
}
}

Instantiation and invocation of the cash register to get change:

public static void main(String[] args) throws IOException {
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(reader);
try {
// Initialise cash register.
CashRegister cashRegister = new CashRegister();
cashRegister.init();
double purchasePrice = Double.parseDouble(in.readLine());
double cash = Double.parseDouble(in.readLine());
// Calculate change.
String result = cashRegister.calculateChange(purchasePrice, cash);
System.out.println(result);
} catch (Exception e) {
System.out.println(e);
}
}

Any denominations of coins can be added in Cash register via the init() method. You can also add a lot of other features to Cash register like

  • Maintain a balance.
  • Support to add new denominations dynamically.
  • Support to remove denomination dynamically.

huangapple
  • 本文由 发表于 2020年8月11日 00:40:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/63344368.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定