Java - 如何遍历2个数组列表并添加值

时间:2013-12-08 03:43:42

标签: java

我有一个文本文件,其中包含日期/时间,名称,金额,总提示

我能够将它简化为名字(在一个arraylist中)和数量倾斜(在第二个arraylist中)

现在IM正试图将它添加到每个人倾斜的数量。

因此,如果X倾斜10,20,30,40,则输出X倾斜100。

来自文字档案

Dec. 6, 2013, 8:31 p.m.  Tip from y
25  7687
Dec. 6, 2013, 8:30 p.m.  Tip from x
30  7662
Dec. 6, 2013, 8:30 p.m.  Tip from z
25  7632
Dec. 6, 2013, 8:31 p.m.  Tip from z
25  7687
Dec. 6, 2013, 8:30 p.m.  Tip from z
30  7662
Dec. 6, 2013, 8:30 p.m.  Tip from x
25  7632

这是我到目前为止的地方

import java.io.*;
import java.util.*;

public class TipTester {

public static void main(String[] args) {
    int lineNumber = 1;
    List<String> name = new ArrayList<String>();
    List<String> tip = new ArrayList<String>();
    String fileName = "C:\\Users\\David\\Desktop\\tips.txt";

    System.out.println("Reading text from file");

    try {
        FileReader inputFile = new FileReader(fileName);
        BufferedReader bufferedReader = new BufferedReader(inputFile);
        String line;

        while ((line = bufferedReader.readLine()) != null) {
            if (lineNumber % 2 != 0) {
        System.out.println(line.substring(line.indexOf("from ") + 5) + "\\");
                name.add(line.substring(line.indexOf("from ") + 5) + "\\");

            } else {
                System.out.println(line.substring(0, line.indexOf("\t")) + "\\");
                tip.add(line.substring(0, line.indexOf("\t")) + "\\");
            }
            lineNumber ++;
        }
        bufferedReader.close();
        name.add("-");
        tip.add("-");
    } catch (Exception e) {
        System.out.println("Error while reading file line by line: " + e.getMessage());
        }
    }
}

1 个答案:

答案 0 :(得分:0)

试试这个

tip.add("-"); // take this line out...
double totalTip = 0; // an accumulator.
for (String tipStr : tip) {
  if (tipStr != null) {
    try {
      totalTip += Double.valueOf(tipStr.trim()); // Add the tips.
    } catch (NumberFormatException e) {
    }
  }
}
System.out.println("totalTip = " + totalTip);