将用户输入的双打列表添加到数组中
问题描述:
因此,我的程序在实例化时询问用户需要多少“项目”。然后,我的程序创建两个数组,一个用于“商品名称”,一个用于“商品价格”。我使用一个循环让用户在各自的数组中输入每个项目名称和项目价格,但是我失去了项目价格数组。为了使用我的循环,我需要使用“itemprice.length”元素,但是当我不使用字符串时,我无法做到这一点。用户输入每个项目的“价格”将用户输入的双打列表添加到数组中
后,我需要一个乘法器应用到每个数组项,并将其输出。所以我想,例如,在数组中有三个项目: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;
}
答
可以作为尝试:
System.out.println("Enter the sales tax: ");
double salesTax = keybd.next();
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 * salesTax);
total = total + cost;
}
System.out.println("Total: " + (total-totalTax));
编辑:插入期间费用计算总。
答
我不清楚你的问题是什么。您是否遇到物料成本数据问题?你只是阅读一个字符串。你应该读一读双数组。
costArray = new double[anyAmountOfItems];
// Then when reading use the appropriate Scanner method
costArray[indexb] = keybd.nextDouble();
一对夫妇的风格说明:
- 你可能要考虑使用,而不是数组列表。这样你就不必担心修复数组的大小。
- 没有必要在每个for循环中使用新的变量名称。它只是增加了混淆。而不是indexa,indexb等只是使用i。
-
更重要的是,使用增强的for循环的情况下,你真的不需要索引:
为(字符串项:itemArray){ 的System.out.println(项目); }
答
使用Float[]
和使用Float.parseFloat(String str)
从字符串到浮点转换。
顺便说一句,与金钱打交道时,浮点是一个坏主意,因为总是有精确的问题。最好是使用带有适当的最低货币单位整数/多头(即美分,在美国等)
如果你需要更多的人不要使用指数A/B/C的名字没有特别的原因,只是我和J,K,L,但在这里,他们生活在不同的范围,所以你可以使用我再次第二个互动。然后,代码不是OOP。如果itemArray.length必须相同,那么对于成本和物料,您将创建一个具有属性(price,total)的复合类Item,并在物料上创建一个Array,并且每个物料和一个netto价格自动创建一个总数。如果可能的话(而不是主题'数组'的作业),你最好使用ArrayList而不是数组。 – 2011-04-28 18:21:54