0

From a text file I am trying to get the the 3rd set of data (type = double) in a row and then sum it up to get the total. My problem is that I am having trouble figuring out how to grab a specific piece of data out of a line with a buffered file reader. I know how to get the line, but parsing the data is the mystery. I have placed my code below in case it may help give more context. Thanks!

EDIT: Please bear with me. I'm literally within my first month of learning Java. I have to use buffered reader. This is a school project. Am I supposed to use "split"? If so can I store the "next split" or something into and array?

listings.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

Code

    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);}
        }
    }
xlecoustillier
  • 16,183
  • 14
  • 60
  • 85

1 Answers1

0

Here is an example, that works (without a file):

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);
    }
}
Moritz Petersen
  • 12,902
  • 3
  • 38
  • 45
  • Ok, I will give it a try. It will be a minute before I can get it functioning enough I think. Ill let you know if this is gonna work out for me. Thanks! – Random-Guy77 May 18 '12 at 15:49
  • ops, there was a mistake in my answer. Corrected it now. – Moritz Petersen May 18 '12 at 15:56
  • I am trying to figure out how to use double total cost as a buffer, but I am having a little trouble. Could you help me out with that? I appreciate your time. – Random-Guy77 May 18 '12 at 16:01
  • Ah, "buffer" is probably the wrong term. Right after `int count = 0;` insert a new line with `double totalCost = 0.0;` – Moritz Petersen May 18 '12 at 16:03
  • I have added the code suggested. The output suggests that the program only passes through the while loop once. At the end count = 1 and totalCost = 0 in the console output. – Random-Guy77 May 18 '12 at 16:15
  • The big question is: how is your data delimited. Is it really a "tab"? That could be the reason it doesn't work. The other question is: why do you need the `DataInputStream`? Is that part of the homework, maybe you should use the `readInt()`, `readDouble()` methods of it? – Moritz Petersen May 18 '12 at 16:18
  • There are four spaces between each of the data sets. – Random-Guy77 May 18 '12 at 16:20
  • Ok, that answers my first question. I updated my answer. Now to my second question ;-) – Moritz Petersen May 18 '12 at 16:24
  • I have to use a buffered FileReader. I don't know if I can use readInt() or readDouble() with that. Let me try and implement the code. – Random-Guy77 May 18 '12 at 16:36
  • This gets the data I am looking for, however it is still only going through the loop once. Is there something wrong with my while loop? – Random-Guy77 May 18 '12 at 16:44
  • a) What do you mean with "this"? Please update your code, so I can see, what you have done. b) At least one problem is, that you don't handle the exception properly. Add `e.printStackTrace()` in the `catch (Exception e) {}` block, and see what you get... – Moritz Petersen May 18 '12 at 16:57
  • It is giving me a NumberFormatException: empty String at the line - totalCost =Double.parseDouble(line.split(" ")[8]); -- If I remove the e.printStackTrace() then the error goes away. – Random-Guy77 May 18 '12 at 17:15
  • :-D no, the error doesn't go away; the error message is just not displayed. You need to learn how to debug your code... So, `split()` is the wrong approach. Use `StringTokenizer`. I updated my answer. – Moritz Petersen May 18 '12 at 17:21
  • After some checking the formatting I have got this program to work. Thanks a lot for your help. If the text file had not had a static amount of spaces between the sets of data, which was the case, how could I have addressed that? – Random-Guy77 May 18 '12 at 17:30
  • You need to know exactly the structure of your input. So, for example, it could be delimited (then `split()` would have been a good choice, as with `StringTokenizer`, or better: a dedicated library, such as [OpenCSV](http://opencsv.sourceforge.net/)) or it could be "indexed", with each set at the same position. Then you could just use `line.subString(...)`. – Moritz Petersen May 18 '12 at 17:34