有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java对数组中的每个项应用乘法

好,,因此,我试图创建一个“销售税程序”,用户可以在其中输入项目,并将其添加到一个数组中,称为“costArray”。我几乎只知道如何使用字符串(因为我需要costArray.length用于循环),但我有点迷路了。有人能帮我指出正确的方向吗?这样我就可以:获取一个数字数组(双倍)并对其应用乘数(0.08表示销售税百分比)并输出总数(双倍)?这是到目前为止我所拥有的,你能告诉我我是否接近吗?谢谢

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;
    }
    //         /**
    //          * Mutator method to calculate tax on each item
    //          */
    //         public void calculateTax(){
    //             for(int index=0; index < costArray.length; index++){
    //                 System.out.println(0.08 * costArray[index]);
    //             }
    //         }
    }

共 (3) 个答案

  1. # 1 楼答案

    在Java 8中:

    import java.util.stream.DoubleStream;
    
    double taxCoef = 0.08;
    double[] prices = {10,20,30};
    double total = DoubleStream.of(prices).map(p->p*(1+taxCoef)).sum();
    
    System.out.println(total);
    

    输出:64.80000000000001

    (或者,可以先求和再相乘)

  2. # 2 楼答案

    如果你不知道数组的大小,那么数组是个坏主意。为什么不使用ArrayList?如果你不知道它的权利知道:你真的会经常需要它

    循环中的索引名称与“i”、“n”、“p、q、r”或“x”非常匹配,它们只存在于自己的循环中,因此您可以在第二个循环中定义一个新的“i”——无需使用indexa、indexb等

    对于学习来说,一个double可能就足够了,但在现实世界中,不应该使用double来表示金钱金额,而应该使用BigDecimal。分数的位表示会产生令人惊讶的效果

    扫描器已经有了像扫描器这样的方法。nextDouble()读取一个数字

  3. # 3 楼答案

    数字存储在字符串中,必须将其“转换”为实数(双倍值)

    方法如下所示:

     String s = "-1.234";
     double value = Double.parseDouble(s);