2011-04-28 60 views
1

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

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)); 
} 
} 
+0

你意识到你没有以任何有意义的方式使用这些数组,对吧?这到底是什么意思? – 2011-04-28 19:56:33

+0

数组包含所有商品的价格。然后我乘以每个数组项并输出它。 – tekman22 2011-04-28 19:59:30

+0

我建议添加你的主要方法,以便给你一个更好的程序流程概念,并可能有助于描述你的类。另外,家庭作业标签将会很好。 – Riggy 2011-04-28 19:59:57

回答

0

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

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) { ... } 
} 

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

0

你的代码是一个烂摊子 - 变量名称混乱,有一段代码中的注释,不必要的拆箱环路...

如果你想利用双值的数组和繁殖的每个值有一些常量的数组,那么用Iterator在你的下一个()方法中做一些自定义List类呢?在迭代集合时,您会得到相乘的数字,并保持原始值不变。

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