从文本文件中的数据创建ArrayList

时间:2015-07-02 01:33:35

标签: java arraylist

我正在尝试编写一个程序,该程序使用两个类来查找零售交易的文本文件中的总金额。第一个类必须读取文件,第二个类必须执行计算。我遇到的问题是,在第一个类中,ArrayList似乎只得到文件中最后一项的价格。这是输入(在文本文件中):

$ 69.99 3鞋子

$ 79.99 1裤子

$ 17.99 1腰带

这是我的第一堂课:

class ReadInputFile {
static ArrayList<Double> priceArray = new ArrayList<>();
static ArrayList<Double> quantityArray = new ArrayList<>();

static String  priceSubstring = new String();
static String quantitySubstring = new String();

public void gatherData () {

String s = "C:\\filepath";   
try {


      FileReader inputFile = new FileReader(s);

      BufferedReader bufferReader = new BufferedReader(inputFile);

      String line;

      String substring = " ";

      while ((line = bufferReader.readLine()) != null)


      substring = line.substring(1, line.lastIndexOf(" ") + 1);



     priceSubstring = substring.substring(0,substring.indexOf(" "));

      quantitySubstring = substring.substring(substring.indexOf(" ") + 1 , substring.lastIndexOf(" ") );


      double price = Double.parseDouble(priceSubstring);
      double quantity = Double.parseDouble(quantitySubstring);

      priceArray.add(price);
      quantityArray.add(quantity);

      System.out.println(priceArray);


} catch (IOException e) {
     e.printStackTrace();
}
}

priceArray的输出和值是[17.99],但是所需的输出是[69.99,79.99,17.99]。

不确定问题出在哪里,但提前感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

基本上你拥有的是:

while ((line = bufferReader.readLine()) != null) {
    substring = line.substring(1, line.lastIndexOf(" ") + 1);
}

priceSubstring = substring.substring(0,substring.indexOf(" "));

quantitySubstring = substring.substring(substring.indexOf(" ") + 1 , substring.lastIndexOf(" ") );


double price = Double.parseDouble(priceSubstring);
double quantity = Double.parseDouble(quantitySubstring);

priceArray.add(price);
quantityArray.add(quantity);

System.out.println(priceArray);

所以你要做的就是创建你刚读过的行的substring,然后阅读下一行,所以基本上,只剩下最后一行的substring将由剩余的代码处理。

{...}中包含要在循环的每次迭代中执行的代码

例如......

while ((line = bufferReader.readLine()) != null) {
    substring = line.substring(1, line.lastIndexOf(" ") + 1);
    priceSubstring = substring.substring(0,substring.indexOf(" "));

    quantitySubstring = substring.substring(substring.indexOf(" ") + 1 , substring.lastIndexOf(" ") );

    double price = Double.parseDouble(priceSubstring);
    double quantity = Double.parseDouble(quantitySubstring);

    priceArray.add(price);
    quantityArray.add(quantity);

    System.out.println(priceArray);
}

这将为文件的每一行执行{...}块内的所有代码