[java] How do I write a method to calculate total cost for all items in an array?

I'm stuck. This is what I have written so far, but I don't know how to set up for a method call to prompt for the total. I need the individual totals for all items in the array to be added to get a total cost and it needs to be displayed at the end of the program. Please, any advice is helpful. I have to be to work soon and need to turn it in before I go. Thanks

MAIN FILE

package inventory2;
import java.util.Scanner;

    public class RunApp
{
        public static void main(String[] args)
{

        Scanner input = new Scanner( System.in );

        Items theItem = new Items();

        int number;
        String Name = "";

    System.out.print("How many items are to be put into inventory count?:  ");
    number = input.nextInt();
    input.nextLine();

    Items[]inv = new Items[number];


     for(int count = 0; count < inv.length; ++count)
            {
                    System.out.print("\nWhat is item " +(count +1) + "'s name?:  ");
                            Name = input.nextLine();
                            theItem.setName(Name);

                    System.out.print("Enter " + Name + "'s product number:  ");
                            double pNumber = input.nextDouble();
                            theItem.setpNumber(pNumber);

                    System.out.print("How many " + Name + "s are there in inventory?:  ");
                            double Units = input.nextDouble();
                            theItem.setUnits(Units);

                    System.out.print(Name + "'s cost: ");
                            double Price = input.nextDouble();
                            theItem.setPrice (Price);

                    inv[count] = new Items(Name, Price, Units, pNumber);
                    input.nextLine();

                        System.out.print("\n Product Name:     " + theItem.getName());
                        System.out.print("\n Product Number:     " + theItem.getpNumber());
                        System.out.print("\n Amount of Units in Stock:     " + theItem.getUnits());
                        System.out.print("\n Price per Unit:   " + theItem.getPrice() + "\n\n");
                        System.out.printf("\n Total cost for %s in stock: $%.2f", theItem.getName(), theItem.calculateTotalPrice());
                    System.out.printf("Total Cost for all items entered: $%.2f", theItem.calculateTotalPrice());    //i need to prompt for output to show total price for all items in array
            }
    }
}

2ND CLASS

package inventory2;

    public class Items
{
       private String Name;
       private double pNumber, Units, Price;          

public Items()
{
Name = "";
pNumber = 0.0;
Units = 0.0;
Price = 0.0;
}

    //constructor
public Items(String productName, double productNumber, double unitsInStock, double unitPrice)
{
    Name = productName;
    pNumber = productNumber;
    Units = unitsInStock;
    Price = unitPrice;
}
    //setter methods
public void setName(String n)
{
    Name = n;
}

public void setpNumber(double no)
{
    pNumber = no;
}

public void setUnits(double u)
{
    Units = u;
}

public void setPrice(double p)
{
    Price = p;
}

//getter methods
public String getName()
{
return Name;
}

public double getpNumber()
{
return pNumber;
}

public double getUnits()
{
return Units;
}

public double getPrice()
{
return Price;
}

public double calculateTotalPrice()
{
    return (Units * Price);
}

public double calculateAllItemsTotalPrice()             //i need method to calculate total cost for all items in array
{
    return (TotalPrice  );                              
}

}

This question is related to java arrays methods

The answer is


The total of 7 numbers in an array can be created as:

import java.util.*;
class Sum
{
   public static void main(String arg[])
   {
     int a[]=new int[7];
     int total=0;
     Scanner n=new Scanner(System.in);
     System.out.println("Enter the no. for total");

     for(int i=0;i<=6;i++) 
     {
       a[i]=n.nextInt();
       total=total+a[i];
      }
       System.out.println("The total is :"+total);
    }
}

In your for loop you need to multiply the units * price. That gives you the total for that particular item. Also in the for loop you should add that to a counter that keeps track of the grand total. Your code would look something like

float total;
total += theItem.getUnits() * theItem.getPrice();

total should be scoped so it's accessible from within main unless you want to pass it around between function calls. Then you can either just print out the total or create a method that prints it out for you.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to methods

String method cannot be found in a main class method Calling another method java GUI ReactJS - Call One Component Method From Another Component multiple conditions for JavaScript .includes() method java, get set methods includes() not working in all browsers Python safe method to get value of nested dictionary Calling one method from another within same class in Python TypeError: method() takes 1 positional argument but 2 were given Android ListView with onClick items