如何添加从两个数组乘以得到的值?

时间:2016-05-15 00:56:46

标签: java arrays operations

所以我正在创建一个发票程序,当我必须从两个数组相乘得到的总数时,我陷入了困境。我能够将它们相乘并得到值,但不幸的是,如果我输入多个项目,则会得到多个值。我希望能够添加我得到的总值。

为了给你一个想法,这是我的代码:

 public static void main(String []args){

Scanner input = new Scanner(System.in); 


  String sentinel = "End";

   String description[] = new String[100];

   int quantity[] = new int[100];

   double price [] = new double[100];
   int i = 0;
   // do loop to get input from user until user enters sentinel to terminate data entry
   do
   {
     System.out.println("Enter the Product Description or " + sentinel + " to stop");
     description[i] = input.next();

     // If user input is not the sentinal then get the quantity and price and increase the index
     if (!(description[i].equalsIgnoreCase(sentinel))) {
       System.out.println("Enter the Quantity");
       quantity[i] = input.nextInt();
       System.out.println("Enter the Product Price ");
       price[i] = input.nextDouble();
     }
     i++;
   } while (!(description[i-1].equalsIgnoreCase(sentinel)));


   System.out.println("Item Description: ");
   System.out.println("-------------------");
   for(int a = 0; a <description.length; a++){
     if(description[a]!=null){
      System.out.println(description[a]);
   }
 }  
   System.out.println("-------------------\n");


   System.out.println("Quantity:");
   System.out.println("-------------------");
   for(int b = 0; b <quantity.length; b++){
     if(quantity[b]!=0){
       System.out.println(quantity[b]);
     }
   } 
   System.out.println("-------------------\n");

   System.out.println("Price:");
   System.out.println("-------------------");
   for(int c = 0; c <price.length; c++){
     if(price[c]!=0){
       System.out.println("$"+price[c]);
     }
   } 
   System.out.println("-------------------");

   //THIS IS WHERE I MULTIPLY THE PRICE AND THE QUANTIY TOGETHER TO GET THE TOTAL
   for (int j = 0; j < quantity.length; j++)
   {
     //double total;
     double total;
     total = quantity[j] * price[j];
     if(total != 0){
       System.out.println("Total: " + total);
     }

   }
 }
}

1 个答案:

答案 0 :(得分:1)

在您的上一个for循环中,您只需将项目的数量和价格相乘,并将其作为总值,而不是将其添加到总计中。每次循环时它都会创建一个新的total.To make it better,声明total out of the loop并移动你的if语句

double total = 0.0;
for (int j = 0; j < quantity.length; j++){

  total += quantity[j] * price[j];
}

if(total != 0){
   System.out.println("Total: " + total);
}