Java-分解代码

Java-分解代码,java,Java,如何将此代码分为两个类?我希望Input类处理纯输入,Tax类处理税和结果的加法。这可能吗?所以基本上我想通过第一个类,TaxClass,而不是Input类来打印税收总额,等等。这是我的密码: public class TaxClass { private Input newList; /** * Constructor for objects of class Tax * Enter the number of items */ public TaxClass(int anyAmount

如何将此代码分为两个类?我希望Input类处理纯输入,Tax类处理税和结果的加法。这可能吗?所以基本上我想通过第一个类,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));
}
}

我想你想要的是一个模型和一个控制器。您的控制器将具有处理输入的方法

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类来为您完成大部分工作,这会更好。

您的代码乱七八糟-变量名称混乱,注释中有代码片段,循环中有不必要的拆箱

如果您想获取一个双值数组,并将数组中的每个值与某个常量相乘,那么使用迭代器生成一些自定义列表类,在下一个方法中为您进行数学运算,怎么样?在遍历集合时,会将数字相乘,原始值保持不变


您的输入类将只收集输入列表中的输入,您将使用它来创建列表,并在输出类中循环通过它并打印结果。您还可以制作输入和输出接口并实现它们—更加灵活。

您意识到您没有以任何有意义的方式使用这些数组,对吗?这到底应该做什么?数组保存所有物品的价格。然后,我将每个数组项乘以一个乘法器并输出它。我建议添加main方法,以便更好地了解程序流程,并可能有助于描述您的类。另外,家庭作业标签也不错。我添加了两个类,TaxClass和Input。我的意思是,除了使用一个人的长度作为for循环的边界外,你永远不会访问代码中的数组。@Riggy试图指出的是,如果这是您的全部代码,它将不会运行,因为没有主方法。