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!
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 have to think it the Java way. Completely forget arrays. Create a class (like
Item) with two fields (call themnameandprice) and put everyItemin aLinkedList. Or create a map, like someone else suggested, but that’s less simple and it’s more urgent for you to drop arrays.That even allows you to add a third field afterwards without re-thinking your code. It’s called object-oriented programming.
But also in C you would create a struct enclosing two elements in order not to get crazy. In Java this is even simpler because Java is an high-level object-oriented language, and there’s no memory management for you to do. Just use the facilities the programming language provides. They are many and do work. 🙂