【发布时间】:2011-04-29 02:42:00
【问题描述】:
所以我的程序在实例化时询问用户他们想要多少“项目”。然后我的程序创建了两个数组,一个用于“商品名称”,一个用于“商品价格”。我使用循环让用户在各自的数组中输入每个项目名称和项目价格,但是我迷失了项目价格数组。要使用我的循环,我需要使用“itemprice.length”元素,但当我不使用字符串时,我不能这样做。
用户输入每个项目的“价格”后,我需要对每个数组项目应用乘数并输出。因此,例如,我想在数组中有 3 个项目:1.20、1.30、1.40,然后我希望程序询问我可以输入 0.08 的“销售税”,然后将每个项目乘以 0.08项目并输出总计。
有没有一种方法可以让我的程序正常工作,让用户输入,比如说 5 件商品及其价格,我是否以正确的方式进行操作?有什么方法可以更轻松地做到这一点?谢谢!
public class Input
{
private Scanner keybd;
private String item;
private double cost;
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(){
for(int index=0; index < itemArray.length; index++){
System.out.println("Enter the item name: ");
itemArray[index] = keybd.next();}
for(int indexa=0; indexa < itemArray.length; indexa++){
System.out.println(itemArray[indexa]);
}
for(int indexb=0; indexb < costArray.length; indexb++){
System.out.println("Enter the item cost: ");
costArray[indexb] = keybd.next();}
for(int indexc=0; indexc < costArray.length; indexc++){
System.out.println(costArray[indexc]);
}
}
/**
* Accessor method to return the items cost with tax
*/
public double getTax(){
return costArray.length;
}
【问题讨论】:
-
没有特殊原因你不要使用 indexa/b/c 作为名称,如果你需要更多的 i 和 j,k,l,但是在这里,它们存在于不同的范围内,所以你可以再次使用 i 进行第二次交互。然后,代码不是 OOP。如果 itemArray.length 必须相同,对于成本和项目,您可以创建一个具有属性(价格、总计)的复合类 Item,并在项目上创建一个数组,然后您将自动获得每个项目的总计和净价格.如果可能的话(不是主题“数组”的作业),你最好使用 ArrayList 而不是数组。
标签: java