Search code examples
javaarraysoperations

How can I add the values that I got from multiplying two arrays?


So I am creating an invoice program and I got stuck at the part when I have to get the total I got from multiplying two arrays. I am able to multiply them and I get the values but unfortunately more than one value if I enter more than one item. I want to be able to add the values I get to get a total.

To give you an idea, here's my code:

 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);
     }

   }
 }
}

Solution

  • In your last for loop, you're only multiplying the quantity and the price of the item and putting it as the value of total instead of adding it to total. Also every time it loops it creates a new total.To make it better, declare total out of the loop and move your if statement out

    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);
    }