0

我试图从一个文本文件中连续获取第三组数据(类型=双),然后将其相加得到总数。我的问题是我无法弄清楚如何使用缓冲文件阅读器从一行中获取特定的数据。我知道如何得到这条线,但解析数据是个谜。我将我的代码放在下面,以防它可能有助于提供更多上下文。谢谢!

编辑:请耐心等待。从字面上看,我在学习 Java 的第一个月内。我必须使用缓冲阅读器。这是一个学校项目。我应该使用“拆分”吗?如果是这样,我可以将“下一个拆分”或其他内容存储到数组中吗?

清单.txt

Int           string(?) double   int

PropertyID    Type    Cost     AgentID --(Not in the file. The file only has the data)

100000       Farm    500000.00   101

100001       Land    700000.00   104

代码

    package overview;

    import java.io.*;
    import java.util.*;
    import java.lang.*;
    import java.nio.*;

    public class Overview {

        public static void main(String[] args) throws FileNotFoundException {

            // TODO code application logic here
            int count = 0;  
            double totalCost=0.00;
            ArrayList<Double> propertyID = new ArrayList();


            //Get file name
            Scanner console = new Scanner(System.in);
            System.out.print ("Please enter file name: ");
            String inputFileName = console.next();
            File inputFile = new File(inputFileName);

            // Get the object of DataInputStream
            FileInputStream fstream = new FileInputStream(inputFile);
            DataInputStream in = new DataInputStream(fstream);


            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            String line;

            try {
                while ((line = reader.readLine()) != null) 
                {
                    double x = Double.parseDouble(line.split(" ")[]);
                    propertyID.add(x);;
                    totalCost = Double.parseDouble(line.split(" ")[8]);
                    count++;
                }
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        finally {

            System.out.println("Total properties in list: " + count + "\n"+ "The total cost is: " +totalCost);}
        }
    }
4

1 回答 1

0

这是一个有效的示例(没有文件):

private static final String data = "100000    Farm    500000.00    101\n100001    Land    700000.00    104";

public static void main(String[] args) throws FileNotFoundException {
    int count = 0;
    double totalCost = 0;

    BufferedReader reader = new BufferedReader(new StringReader(data));
    String line;

    try {
        while ((line = reader.readLine()) != null) {
            StringTokenizer stok = new StringTokenizer(line);
            int propertyId = Integer.parseInt(stok.nextToken());
            String type = stok.nextToken();
            double cost = Double.parseDouble(stok.nextToken());
            int agentId = Integer.parseInt(stok.nextToken());

            totalCost += cost;
            count++;
        }
        // close input stream
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    finally {
        System.out.println("Total properties in list: " + count + "\nTotal cost is: " + totalCost);
    }
}
于 2012-05-18T15:47:51.260 回答