Java - Combining two arrays? -
what i'm trying ask user list of items, , create 2 arrays - 1 itemname , 1 itemprice. program right deals itemprice , there's no indication of how can combine 2 arrays in 1 output list of both arrays combined, this:
bread - 1.20
milk - 2.00
here have far, 2 arrays, name array isn't included in anything. thanks!
public class taxclass { private input newlist; /** * constructor objects of class tax * enter number of items */ public taxclass(int anyamount) { newlist = new input(anyamount); } /** * mutator method add items , cost * enter 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 objects of class scanner */ public input(int anyamountofitems) { keybd = new scanner(system.in); costarray = new string[anyamountofitems]; itemarray = new string[anyamountofitems]; } /** * mutator method set item names , costs */ public void setarray(double anyvalue){ for(int index=0; index < itemarray.length; index++){ system.out.println("enter 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 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 think java way. completely forget arrays. create class (like item
) 2 fields (call them name
, price
) , put every item
in linkedlist
. or create map, else suggested, that's less simple , it's more urgent drop arrays.
that allows add third field afterwards without re-thinking code. it's called object-oriented programming.
but in c create struct enclosing 2 elements in order not crazy. in java simpler because java high-level object-oriented language, , there's no memory management do. use facilities programming language provides. many , work. :)
Comments
Post a Comment