Java - 分解代码

标签 java

我如何将这段代码分成两个类?我希望输入类处理纯粹的输入,而税收类处理税收和结果的添加。这可能吗?所以基本上我想通过第一个类 TaxClass 而不是 Input 类来打印税收总额等。这是我的代码:

public class TaxClass
{
private Input newList;
/**
 * Constructor for objects of class Tax
 * Enter the number of items
 */
public TaxClass(int anyAmount)
{
    newList = new Input(anyAmount);
}
/**
 * Mutator method to add items and their cost
 * Enter the sales tax percentage
 */
public void addItems(double anyTax){
    double salesTax = anyTax;
    newList.setArray(salesTax);
}
}

public class Input
{
private Scanner keybd;
private String[] costArray;
private String[] itemArray;

/**
 * Constructor for objects of class Scanner
 */
public Input(int anyAmountofItems)
{
    keybd = new Scanner(System.in);
    costArray = new String[anyAmountofItems];
    itemArray = new String[anyAmountofItems];
}
/**
 * Mutator method to set the item names and costs
 */
public void setArray(double anyValue){
    //System.out.println("Enter the sales tax percentage: ");
    //double salesTax = keybd.nextDouble();
    double totalTax=0.0;
    double total=0.0;
    for(int indexc=0; indexc < costArray.length; indexc++){
       System.out.println("Enter the item cost: ");
       double cost = Double.valueOf(keybd.next()).doubleValue();
       totalTax = totalTax + (cost * anyValue);
       total = total + cost;
    }
    System.out.println("Total tax: " + totalTax);
    System.out.println("Total cost pre-tax: " + total);
    System.out.println("Total cost including tax: " + (total+totalTax));
}
}

最佳答案

我认为你想要的是一个模型和一个 Controller 。您的 Controller 将具有处理输入的方法。

public class InputController {
    public int getCost() { ... }
    public void promptUser() { ... }
}

您的模型将是一个具有成本和税费的项目。

public class TaxableItem {
    private int costInCents;
    private int taxInCents;
    public int getTotal();
    public int getTaxInCents() { ... }
    public void setTaxInCents( int cents ) { ... }
    public int getCostInCents() { ... }
    public void setCostInCents( int cents ) { ... }
}

然后在您的 main 方法中,您将创建一组 TaxableItem 对象,每个用户输入一个对象。您还可以创建一个 Receipt 类来为您完成大部分工作,这样会更好。

关于Java - 分解代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5824151/

相关文章:

java - 使用库编写 java unix 命令

java - 算法的复杂性和大哦符号

java - eclipse Spring MVC 4 +Hibernate 和 MySQL + Tiles.xml 中的 HTTP 状态 404

java - 在Group之上展开Android的ExpandableListView Children

java - 在我的 java 应用程序中使用 alfresco Rest-API 但找不到方法

java - 如何在Spring Security中为两个不同的URL指定两个不同的登录表单?

java - 如何创建仅包含偶数的数组的副本?

java - 样式表不适用于 JavaFx

java - 在java中调整二维数组的大小

java - mtime.sec 不存在