PDA

View Full Version : Two Dimensional Array


Hallucination
06-16-2009, 02:00 AM
First code is the helper class second is the app class. After processing all the information display the results in tabular format. Each column represents a particular salesperson and each row representing a particular product and at the bottom of each row and column will have the totals for each. I don’t even know where to start. Just point me in the right direction. I’m not sure how to set up the rows and columns, stupid book is no help just confuses me even more. Should look like that but spaced out right.
Salesperson1 Salesperson2 Salesperson3 Salesperson4 totals
Product1 2 2 2 2 8
Product2 2 2 2 2 8
Product3 2 2 2 2 8
Product4 2 2 2 2 8
Product5 2 2 2 2 8
totals 10 10 10 10 80




public class Sales
{
// declares variable
private double sales [][];
private int people;
private int products;
double _sales;
double total;


Sales (int numPeople, int numProducts)
{
people = numPeople;
products = numProducts;
sales = new double [numPeople] [numProducts];

for (int row = 0; row < numPeople; row++)
{
for (int column = 0; column < numProducts; column++)
{
sales [row] [column] = 0;
}
}

}

public double acceptSales(int person, int product, double salesAmount)
{
sales [person][product] = salesAmount;
return total;
}

public double getSalesByPerson (int person)
{
_sales = 0.0;
for (int i = 0; i < sales.length; i++)
{
_sales += sales[person][i];
}
return _sales;
}

public double getSalesByProduct (int product)
{
total = 0.0;
for (int i = 0; i < sales.length; i++)
{
total += sales[i][product];
}

return total;

}

public double getTotalSales()
{
total = 0.0;
for (int i = 0; i < people; i++)
{
for (int j = 0; j < products; j++)
{
total =total + sales[i][j];
}
}
return total;
}

}


public class TotalSales
{

public static void main(String[] args)
{

int PEOPLE = 4;
int PRODUCTS = 5;
double userSales;
Scanner input = new Scanner(System.in);
Sales mySales = new Sales(PEOPLE, PRODUCTS);


for (int i = 0; i < PEOPLE; i++)
{
for (int j = 0; j < PRODUCTS; j++)
{

System.out.print("Enter total value for product" + (j + 1));
System.out.print(" sold by salesperson"+ (i + 1) +": ");
userSales = input.nextDouble();
mySales.acceptSales(i, j, userSales);
}
}

System.out.println();
for (int i = 0; i < PEOPLE; i++)
{
System.out.printf("Person %d total sales: $%.2f\n", (i + 1),
mySales.getSalesByPerson(i));
}

System.out.println();
for (int i = 0; i < PRODUCTS; i++)
{
System.out.printf("Product %d total sales: $%.2f\n", (i + 1),
mySales.getSalesByProduct(i));
}

System.out.printf("TOTAL SALES: $%.2f\n", mySales.getTotalSales());
}
}