在这个程序中,我有一个带有高尔夫分数的文本文件,我已将每个高尔夫球手的分数添加到ArrayList中。我需要在每个ArrayList中得到这些分数的总和,以得到每个高尔夫球手的总数。
File golf = new File("golf.txt");
Scanner scan = new Scanner(golf);
int i = 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++;
}
for (int j : par)
{
parsum += j;
}
for (int j : golfer1)
{
golfsum1 += j;
}
for (int j : golfer2)
{
golfsum2 += j;
}
for (int j : golfer3)
{
golfsum3 += j;
}
for (int j : golfer4)
{
golfsum4 += j;
}
无论如何都要更快地做到这一点,而不是有5个增强的for循环
答案 0 :(得分:3)
File golf = new File("golf.txt");
Scanner scan = new Scanner(golf);
int i = 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++;
}
这样,您可以在扫描时直接添加并将其存储在列表中,但避免对列表进行不必要的迭代以获得总计。
答案 1 :(得分:0)
如果您使用的是Java 8,请使用IntStream
:
http://www.deadcoderising.com/2015-05-19-java-8-replace-traditional-for-loops-with-intstreams/
另外,考虑线程化每个求和任务,虽然它是高尔夫分数(琐碎,小任务),但开销可能成本过高。