-
Java combining arrays
What I'm trying to do is ask the user for a list of items, and create two arrays - one for the itemName and one for the itemPrice. My program right now deals only with the itemPrice and there's no indication of how I can combine two arrays in one to output a list of both arrays combined, like this:
Bread - 1.20
Milk - 2.00
Here is what I have so far, two arrays, but the name array really isn't included in anything. Thanks!
Code:
public class TaxClass
{
private Input newList;
/**
* Constructor for objects of class Tax
* Enter the number of items
*/
public TaxClass(int anyAmount)
{
newList = new Input(anyAmount);
}
/**
* Mutator method to add items and their cost
* Enter the sales tax percentage
*/
public void addItems(double anyTax){
double salesTax = anyTax;
newList.setArray(salesTax);
}
}
public class Input
{
private Scanner keybd;
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(double anyValue){
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]);
double totalTax=0.0;
double total=0.0;
for(int indexc=0; indexc < costArray.length; indexc++){
System.out.println("Enter the item cost: ");
double cost = Double.valueOf(keybd.next()).doubleValue();
totalTax = totalTax + (cost * anyValue);
total = total + cost;
}
System.out.println("Total tax: " + totalTax);
System.out.println("Total cost pre-tax: " + total);
System.out.println("Total cost including tax: " + (total+totalTax));
}
}
-
You don't need to combine the arrays to get the output you desire. Just access each array and concatenate them to a single line:
Code:
...
System.out.println(itemArray[index] + " - " + costArray[index]);
...
-
When I do that it comes up like this:
Milk-null
Bread-null
Cookies-null
Chocolate-null
Cereal-null
Total tax: 0.52
Total cost pre-tax: 6.5
Total cost including tax: 7.02
-
You never store the cost in your costArray[]. Look in your for loop, you retrieve the item cost, but you never actually store it in the costArray.
-
-
You set the costArray the same way you set your itemArray. Does the cost variable hold the value that you need? If so, you would set it like this:
Code:
...
double cost = Double.valueOf(keybd.next()).doubleValue();
costArray[indexc] = cost;
...