Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 9 of 9

Thread: I/O Program output error

  1. #1
    Junior Member
    Join Date
    Mar 2012
    Posts
    16
    My Mood
    Stressed
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default I/O Program output error

    Hello All,

    I am working on a program that requries me to read and analyze a .txt file and output the results to a .txt file, but I am getting incorrect output. I have been successfull with part of the program in that it reads the text file and analyzes it, however I need it to take the key(which is Agent ID) and add together the total of the value(which is pValue), however the output just shows each Agent ID and then each pValue. I do not know how to take all the AgentID's and add their pValues together to output the total. I also need the pValues to be in decimal format like(#.##), but I can't seem to get that to work either. Can anyone offer some suggestions?

    I thank you in advance for any help.

    Here is the code I have come up with so far:

    package gtt1_task2;
     
    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 zubeda.a.hemani
     */
     
    //This program reads a text file, analyzes property listings and outputs a report to a text file
     
    public class GTT1_Task2 {
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args)throws FileNotFoundException {
     
            // Prompts the user for the input file name (listings.txt) by creting a scanner object
     
            Scanner listings = new Scanner(System.in);
            //Ask user for file name
     
            System.out.print("Input File:   ");
            String inputFileName = listings.next();
     
            //Use unbuffered file to open text file(listings.txt) and read in property listings.
     
            BufferedWriter pwfo = null;
     
            try{
                pwfo = new BufferedWriter(new FileWriter("C:\\Users\\zubeda.a.hemani\\Documents\\NetBeansProjects\\GTT1_Task2\\src\\gtt1_task2\\listings.txt", true));
               } catch (IOException e){    
               }
               PrintWriter pwo = new PrintWriter(pwfo);
     
               //Construct property type treeSet
     
               Set<String> propertyTypes = pTypes(inputFileName);
     
               //Print property types from treeSet
     
               for(String type: propertyTypes)
               {
                   System.out.println(type);
                   pwo.println(type);
               }
               //pwo.flush();
               //pwo.close();
     
              //Construct agent id and value treeSet
                   Set<String> agentRpt = agentValue(inputFileName);
              //Print agent id and values from key set    
                   for(String tail: agentRpt)
                   {   
                       {
                           System.out.println(tail);
                           pwo.println(tail);
                       }
                   }
                   pwo.flush();
                   pwo.close();
                   }   
         /**
            Reads the input file.
            @param inputFileNamegre
            @return the alphabetized property types in uppercase.
         */
         public static Set<String> pTypes(String inputFileName)
            throws FileNotFoundException
     
            //Construct a tree set to return the property types
          {
            Set<String> type = new TreeSet<String>();
            Scanner in = new Scanner(new File(inputFileName));
     
            // Use delimiters to select specific chars for set
     
            in.useDelimiter("[1234567890. ]");
     
            while (in.hasNext())
            {
              type.add(in.next().toUpperCase());
            }
            in.close();
     
            return type;
          }
         /**
            Reads the input file.
            @param inputFileName
            @returns the Agent id's and corresponding property values.
         */
         public static Set<String> agentValue(String inputFileName)
            throws FileNotFoundException
         {
             TreeSet<String> tail = new TreeSet<String>();
             SortedMap<String, Number> agentValues = new TreeMap<String, Number>();
             Scanner in = new Scanner(new File(inputFileName));
             String line = inputFileName;
     
           while (in.hasNext())
           {
                   try {
             line = in.nextLine();
             String[] fields = line.split("[\\s}]");
             String agentId = (fields [3]);
             Double pValue = Double.parseDouble(fields [2]);
     
                     if (agentValues.containsKey(agentId))
                {
             pValue += agentValues.get(agentId).doubleValue();
                }
                     agentValues.put(agentId, pValue);
     
                  }catch  (Exception e) {
                                      }
         // Create keyMap with all keys and values
     
                Set<String> keySet = agentValues.keySet();
                for (String key : keySet)
                        {
                Number value = agentValues.get(key);
         //System.out.println(key + "\t" + value);
                        tail.add(key + "\t" + value);
                        }
                   }
           return tail;
           }
       }


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: I/O Program output error

    Can you post the output that is created, explain what is wrong with it and show what you want it to be.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Mar 2012
    Posts
    16
    My Mood
    Stressed
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: I/O Program output error

    Thanks for your response.

    Here is the ouptut I am getting:

    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

    But what I need to have is:

    COMMERICAL
    FARM
    LAND
    RESIDENTIAL

    101 600000.00
    105 30000.00
    106 200000.00
    107 1040000.00
    110 250000.00

    This output shows the key(Agent ID) with their corresponding value(pValues) added together, whereas my current output just shows each agentID and each pValue but doesn't add them together. Also, I need to figure out how to get the output to show the pValues as a decimal with 2 places.

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: I/O Program output error

    Look at the DecimalFormat class. It can be used to format the output to have the 2 decimal places.

    The code needs to look at the key for the next line and if it is the same, then add the value to the current value.
    Don't print the current values until a new key value is read.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Mar 2012
    Posts
    16
    My Mood
    Stressed
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: I/O Program output error

    Thank you for the advice. I will give that a try and see what happens.

  6. #6
    Junior Member
    Join Date
    Mar 2012
    Posts
    16
    My Mood
    Stressed
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: I/O Program output error

    Thanks again...I was able to figure out the decimal format class and get that to work, however I am still having trouble with adding my agent id values. I am assuming I need an if else statement, but I am not sure how to go about it for this problem. It may be that it is a simple task, but I am so new to Java that even small things tend to stump me for awhile. Any suggestions? I did view the stock analyzer video tutorials on this site, but I didn't see anything that would help me here. I have been working on this for a few hours now and can't seem to get anywhere, so any help or direction you can provide is greatly appreciated.

  7. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: I/O Program output error

    Some pseudo code:
    read a first line and save data for the first agent as current agent
    begin loop to read through rest of data in the file
    Read next line of data from file
    Is this data for current agent?
    If same agent, get value and add to current value for this agent
    If new agent, write out the data for the old agent and start saving data for this agent
    end loop
    If you don't understand my answer, don't ignore it, ask a question.

  8. #8
    Super Moderator Sean4u's Avatar
    Join Date
    Jul 2011
    Location
    Tavistock, UK
    Posts
    637
    Thanks
    5
    Thanked 103 Times in 93 Posts

    Default Re: I/O Program output error

    That's not an easy bug to spot! You have a 'curly bracket' in the wrong place. Uncomment your System.out.println in the loop that builds your output list and put in another System.out.println near the top of the while loop in agentValue(...), say for example where you augment your individual agent value, and you'll soon see from the output where you've gone wrong.

    That would have been much easier if your code had sane indentation.

  9. #9
    Junior Member
    Join Date
    Mar 2012
    Posts
    16
    My Mood
    Stressed
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: I/O Program output error

    Quote Originally Posted by Sean4u View Post
    That's not an easy bug to spot! You have a 'curly bracket' in the wrong place. Uncomment your System.out.println in the loop that builds your output list and put in another System.out.println near the top of the while loop in agentValue(...), say for example where you augment your individual agent value, and you'll soon see from the output where you've gone wrong.

    That would have been much easier if your code had sane indentation.
    I do apologize for the indentation...I am still so new with JAVA that I am not as organized as I would like. Thank you so much for the tip. I will remove the comment and attempt to put a correct System.out.println in the correct place. Thanks again for the response.

Similar Threads

  1. No Error in Code but Output is not desired...!!!
    By Adi in forum What's Wrong With My Code?
    Replies: 1
    Last Post: August 28th, 2011, 08:56 AM
  2. [SOLVED] Need help with input/output error
    By stefan2892 in forum What's Wrong With My Code?
    Replies: 4
    Last Post: February 7th, 2011, 10:44 AM
  3. No Output in Program:
    By bengregg in forum What's Wrong With My Code?
    Replies: 2
    Last Post: January 17th, 2011, 11:01 PM
  4. [SOLVED] Encoder output error heed help
    By SHStudent21 in forum What's Wrong With My Code?
    Replies: 0
    Last Post: January 14th, 2011, 06:47 PM
  5. Redirect error and output stream using java program
    By leenabora in forum File I/O & Other I/O Streams
    Replies: 5
    Last Post: June 16th, 2009, 04:12 AM