gpt4 book ai didi

Java - 分解代码

转载 作者:行者123 更新时间:2023-12-01 05:46:27 24 4
gpt4 key购买 nike

我如何将这段代码分成两个类?我希望输入类处理纯粹的输入,而税收类处理税收和结果的添加。这可能吗?所以基本上我想通过第一个类 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com