java - how to do a sum on many ArrayLists quickly? -
in program have text file golf scores , have added each golfers scores arraylist. need sum of these scores in each arraylist total each golfer.
file golf = new file("golf.txt"); scanner scan = new scanner(golf); int = 0; int parsum = 0, golfsum1 = 0, golfsum2 = 0, golfsum3 = 0, golfsum4 = 0; arraylist<integer> par = new arraylist<integer>(); arraylist<integer> golfer1 = new arraylist<integer>(); arraylist<integer> golfer2 = new arraylist<integer>(); arraylist<integer> golfer3 = new arraylist<integer>(); arraylist<integer> golfer4 = new arraylist<integer>(); while (scan.hasnext()) { par.add(i, scan.nextint()); golfer1.add(i, scan.nextint()); golfer2.add(i, scan.nextint()); golfer3.add(i, scan.nextint()); golfer4.add(i, scan.nextint()); i++; } (int j : par) { parsum += j; } (int j : golfer1) { golfsum1 += j; } (int j : golfer2) { golfsum2 += j; } (int j : golfer3) { golfsum3 += j; } (int j : golfer4) { golfsum4 += j; }
is there anyway quicker, rather having 5 enhanced loops
file golf = new file("golf.txt"); scanner scan = new scanner(golf); int = 0; int parsum = 0, golfsum1 = 0, golfsum2 = 0, golfsum3 = 0, golfsum4 = 0; arraylist<integer> par = new arraylist<integer>(); arraylist<integer> golfer1 = new arraylist<integer>(); arraylist<integer> golfer2 = new arraylist<integer>(); arraylist<integer> golfer3 = new arraylist<integer>(); arraylist<integer> golfer4 = new arraylist<integer>(); while (scan.hasnext()) { final int parvalue = scan.nextint(), golfvalue1 = scan.nextint(), golfvalue2 = scan.nextint(), golfvalue3 = scan.nextint(), golfvalue4 = scan.nextint(); parsum += parvalue; golfsum1 += golfvalue1; golfsum2 += golfvalue2; golfsum3 += golfvalue3; golfsum4 += golfvalue4; par.add(i, parvalue); golfer1.add(i, golfvalue1); golfer2.add(i, golfvalue2); golfer3.add(i, golfvalue3); golfer4.add(i, golfvalue4); i++; }
this way directly add scan , store them in lists, avoid unnecessary iterations of list totals.
Comments
Post a Comment