okay I have it almost complete with one issue: When the report runs it is suppose to add up the property values for each agent and only display the total value of the properties. like:COMMERICAL
FARM
LAND
RESIDENTIAL

101 600000.00
105 30000.00
106 200000.00
107 1040000.00
110 250000.00
but for some reason when I run the report it is adding the property values up but it is also displaying the 1st value of each agent. like:
COMMERCIAL
FARM
LAND
RESIDENTIAL
101:500000.0
101:600000.0
105:30000.0
106:200000.0
107:1000000.0
107:1040000.0
110:250000.0
as can see if you compare to the origional file:
500000.00 101
100000.00 101
1000000.00 107
30000.00 105
200000.00 106
40000.00 107
250000.00 110

it is adding but for some reason it is showing the original agents 1st property and also the amout after the add.
I cannot see what I am missing,

thank you,

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package taska;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.TreeSet;

/**
 *
 * @author chadblack
 */
public class TaskA {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) 

            throws FileNotFoundException
             {
                 //Prompt the user for the name of the input file (listings.txt).
        Scanner getfile = new Scanner(System.in);
    System.out.print("Input file: ");//this displays for the user
    String inputFileName = getfile.next();//this will retrieve the file listings.txt

    BufferedWriter addinfo = null;

    try{
        addinfo = new BufferedWriter(
     new FileWriter("agentreport.txt", true));
    }
    catch(IOException e){
    }
        try (PrintWriter display = new PrintWriter(addinfo)) {
            Set<String> propertyTypes;
                     propertyTypes = pTypes(inputFileName);

            for (String type: propertyTypes)
            {
                System.out.println(type);
                display.println(type);
            }
            //pwo.flush();
            //pwo.close();


            //construct agent ids and vales treeSet
            Set<String> agentRpt = agentValue(inputFileName);
            //print the agents id's
            for (String tail: agentRpt)
            {
                {
                   System.out.println(tail);
                    display.println(tail);
                }
            }
            display.flush();
            display.close();
        }
        }
    /**
     * Reads the Input file
     * 
     * returns the alphabetized property types in correct format
     */
    public static Set<String> pTypes (String inputFileName)
            throws FileNotFoundException
            //now construct treeSet to return the property type
    {
        Set<String> type = new TreeSet<>();
        try (Scanner pt = new Scanner(new File(inputFileName))) {
            pt.useDelimiter("[1234567890.]");

            while(pt.hasNext())
            {
                type.add(pt.next().toUpperCase());
            }
        } 

    return type;

    }
    /**
     * Reads the file
     * returns the agents id's and property values.
     */
    public static Set<String> agentValue(String inputFileName)
            throws FileNotFoundException
    {

        TreeSet<String> tail = new TreeSet<>();
        SortedMap<String, Number> agentValues = new TreeMap<>();
        Scanner in = new Scanner(new File(inputFileName));
        String line = inputFileName;

        while (in.hasNext())
        {

            try {
                line = in.nextLine();
            String[] fields = line.split("[\\s}]");
            String agentnumber = (fields [3]);
            Double propValue = Double.parseDouble(fields [2]);

            if (agentValues.containsKey(agentnumber))

            {
                propValue = agentValues.get(agentnumber).doubleValue();
            }
            agentValues.put(agentnumber, propValue);
            }catch (Exception e){
            }



            Set<String> keySet = agentValues.keySet();

           for (String key : keySet)
                   {
               Number value = agentValues.get(key);
               tail.add(key+ ": "+"$"+ value);

            }
        }

    return tail;

    }

    }

Recommended Answers

All 7 Replies

Golden advice from a quick skim through your code:

Line 122-123: NEVER EVER leave your catch blocks empty! [1] It will hide away every potential error and problem at the time one occurs.
Whenever you feel tempted to leave a catch block empty, always at least insert a call to printStackTrace(), like this:

...
catch (Exception ex)
{
    ex.printStackTrace();
}
...

[1] This is also commonly referred to as "eating the exception". Well, trust me: exceptions taste bad, you don't want to ever eat them :P

^ excellent advice from Tux. Plus: sort out your indentation - it's very hard to see where blocks begin and end and, even worse, its too easy to think that the indentation accurately reflects the block structure of the code when in reality it doesn't.
Finally, use lots of temporary print statements to track the values of key variables and the calls to key methods so you can see where your logic is going wrong.

Re-post your code with formatting fixed and all the exceptions caught and logged. I very much doubt that anyone here is going to spend time trying to debug code that has empty catch blocks.

I took the time trying to reproduce the behaviour you describe in your post, but I don't seem to be able to.
I was getting other errors, most likely because I was guessing at the file structure.
Is this the same code as you were using? Could you provide us with the exact same contents of the input file that you were using at the time you encountered the problem?

On a side note:

Code formatting can be done effortlessly in any decent IDE.
From lines 1-4 I can derive that you're probably using NetBeans.
You can let NetBeans format code for you: Right click in your code editor and choose Format, or use the keyboard shortcut ALT+SHIFT+F.

I'm not sure that the code works as the explanation. I do not see where the total value of sale from an agent is added with its previous value read. Line 119 will retrieve the existing value and reassigns to the key in line 121. In other words, it is not an addition but instead a replacement.

By the way, the key "101" is not equal to "101 " or " 101" because of a white space. When you do the split, you expect only 1 white space before }. If your data contains more than 1 white space before }, you will include that value (white space) in your split result. You may try //s+ instead of //s.

PS: Your logic error is from lines 129~134. You are adding a new string to your set every time you read a line. Even though the key may not be duplicated in a set, the value of key + ":" + some_value will never be equal if the some_value kept changing (and never be the same value) inside the loop. To solve it, you need to move the loop outside your while loop.

PSS: My recommendation when you do this type of programming, you should collect all data first, and then populate/manipulate later. Attempt to collect and populate/manipulate at the same time (inside the same loop) may cause an unexpected result or confusion.

Thank you for your help, here is the code after I used netbeans to format it:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package taska;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.TreeSet;

/**
 *
 * @author Q
 */
public class TaskA {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
            throws FileNotFoundException {
        //Prompt the user for the name of the input file (listings.txt).
        Scanner getfile = new Scanner(System.in);
        System.out.print("Input file: ");//this displays for the user
        String inputFileName = getfile.next();//this will retrieve the file listings.txt

        BufferedWriter addinfo = null;

        try {
            addinfo = new BufferedWriter(
                    new FileWriter("agentreport.txt", true));
        } catch (IOException e) {
        }
        try (PrintWriter display = new PrintWriter(addinfo)) {
            Set<String> propertyTypes;
            propertyTypes = pTypes(inputFileName);

            for (String type : propertyTypes) {
                System.out.println(type);
                display.println(type);
            }
            //pwo.flush();
            //pwo.close();


            //construct agent ids and vales treeSet
            Set<String> agentRpt = agentValue(inputFileName);
            //print the agents id's
            for (String tail : agentRpt) {
                {
                    System.out.println(tail);
                    display.println(tail);
                }
            }
            display.flush();
            display.close();
        }
    }

    /**
     * Reads the Input file
     *
     * returns the alphabetized property types in correct format
     */
    public static Set<String> pTypes(String inputFileName)
            throws FileNotFoundException //now construct treeSet to return the property type
    {
        Set<String> type = new TreeSet<>();
        try (Scanner pt = new Scanner(new File(inputFileName))) {
            pt.useDelimiter("[1234567890.]");

            while (pt.hasNext()) {
                type.add(pt.next().toUpperCase());
            }
        }

        return type;

    }

    /**
     * Reads the file returns the agents id's and property values.
     */
    public static Set<String> agentValue(String inputFileName)
            throws FileNotFoundException {

        TreeSet<String> tail = new TreeSet<>();
        SortedMap<String, Number> agentValues = new TreeMap<>();
        Scanner in = new Scanner(new File(inputFileName));
        String line = inputFileName;

        while (in.hasNext()) {

            try {
                line = in.nextLine();
                String[] fields = line.split("[\\s}]");
                String agentnumber = (fields[3]);
                Double propValue = Double.parseDouble(fields[2]);

                if (agentValues.containsKey(agentnumber)) {
                    propValue += agentValues.get(agentnumber).doubleValue();
                }
                agentValues.put(agentnumber, propValue);
            } catch (Exception e) {
            }



            Set<String> keySet = agentValues.keySet();

            for (String key : keySet) {
                Number value = agentValues.get(key);
                tail.add(key + ": " + "$" + value);

            }
        }

        return tail;

    }
}

here is the listings.txt file content:
110001 commercial 500000.00 101
110223 residential 100000.00 101
110020 commercial 1000000.00 107
110333 land 30000.00 105
110442 farm 200000.00 106
110421 land 40000.00 107
112352 residential 250000.00 110

the only notice that is showing in Netbeans is line 100 it says:
String line = inputFileName; "the assigned value is never used."

existing value

reassigns to the key

PS: Your logic error is from lines 129~134. You are adding a new string to your set every time you read a line. Even though the key may not be duplicated in a set, the value of key + ":" + some_value will never be equal if the some_value kept changing (and never be the same value) inside the loop. To solve it, you need to move the loop outside your while loop.

Thank you for that advice, its been solved I moved it outside the while loop. Very subltle so here now is the correct working code for comparison.

Thank you again for all your help everyone!!!!

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package taska;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.TreeSet;

/**
 *
 * @author Q
 */
public class TaskA {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
            throws FileNotFoundException {
        //Prompt the user for the name of the input file (listings.txt).
        Scanner getfile = new Scanner(System.in);
        System.out.print("Input file: ");//this displays for the user
        String inputFileName = getfile.next();//this will retrieve the file listings.txt

        BufferedWriter addinfo = null;

        try {
            addinfo = new BufferedWriter(
                    new FileWriter("agentreport.txt", true));
        } catch (IOException e) {
        }
        try (PrintWriter display = new PrintWriter(addinfo)) {
            Set<String> propertyTypes;
            propertyTypes = pTypes(inputFileName);

            for (String type : propertyTypes) {
                System.out.println(type);
                display.println(type);
            }
            //pwo.flush();
            //pwo.close();


            //construct agent ids and vales treeSet
            Set<String> agentRpt = agentValue(inputFileName);
            //print the agents id's
            for (String tail : agentRpt) {
                {
                    System.out.println(tail);
                    display.println(tail);
                }
            }
            display.flush();
            display.close();
        }
    }

    /**
     * Reads the Input file
     *
     * returns the alphabetized property types in correct format
     */
    public static Set<String> pTypes(String inputFileName)
            throws FileNotFoundException //now construct treeSet to return the property type
    {
        Set<String> type = new TreeSet<>();
        try (Scanner pt = new Scanner(new File(inputFileName))) {
            pt.useDelimiter("[1234567890.]");

            while (pt.hasNext()) {
                type.add(pt.next().toUpperCase());
            }
        }

        return type;

    }

    /**
     * Reads the file returns the agents id's and property values.
     */
    public static Set<String> agentValue(String inputFileName)
            throws FileNotFoundException {

        TreeSet<String> tail = new TreeSet<>();
        SortedMap<String, Number> agentValues = new TreeMap<>();
        Scanner in = new Scanner(new File(inputFileName));
        String line = inputFileName;

        while (in.hasNext()) {

            try {
                line = in.nextLine();
                String[] fields;
                fields = line.split("[\\s}]");
                String agentnumber = (fields[3]);
                Double propValue = Double.parseDouble(fields[2]);

                if (agentValues.containsKey(agentnumber)) {
      //retrieves the existing value and reassigns to the key             
                    propValue += agentValues.get(agentnumber).doubleValue();
                }

                agentValues.put(agentnumber, propValue);
            } catch (Exception e) {
            }


        }
            Set<String> keySet = agentValues.keySet();
                    for (Iterator<String> it = keySet.iterator(); it.hasNext();) {
                        String key = it.next();
                        Number value = agentValues.get(key);
                        tail.add(key+ ": " + "$" +value);
                    }


        return tail;

    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.