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:

print("code sample");

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;
   }
}
View Answers









Related Tutorials/Questions & Answers:
I/O Program output error
I/O Program output error  Hello All, I am working on a program... 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
Write a program that replaces a, e, i, o, u in Java2
Write a program that replaces a, e, i, o, u in Java2  Write a program that replaces a, e, i, o, u, with the letter z. (i.e. John Smith -> Jzhn Smzth. Also the program reverses the users name (i.e. John Smith -> htimS nhoJ
Advertisements
i/o
i/o  java program using inputstream and outputstream   Hi Friend, Try the following code: import java.io.*; class InputStreamAndOutputStream { public static void main(String[] args)throws
i/o
i/o  java program using inputstream and outputstream   Hi Friend, Try the following code: import java.io.*; class InputStreamAndOutputStream { public static void main(String[] args)throws Exception
i/o
i/o  java program using inputstream and outputstream   Hi Friend, Try the following code: import java.io.*; class InputStreamAndOutputStream { public static void main(String[] args)throws Exception
i/o
i/o  java program using inputstream and outputstream   Hi Friend, Try the following code: import java.io.*; class InputStreamAndOutputStream { public static void main(String[] args)throws Exception
i/o
i/o   Write a Java program to do the following: a. Write into file the following information regarding the marks for 10 students in a test i. Matric no ii. Marks for question 1 iii. Marks for question 2 iv. Marks
Java I/O Examples
; What is Java I/O? The Java I/O means... and Interfaces of the I/O Streams The following listing of classes... provides the standard I/O facilities for reading text through either
Java I/O problem
Java I/O problem   Write a Java application that prompts the user... by line, and output it to the console with the line number. The program should.... The program should use the FileWriter class and an appropriate processing stream
I/O stream class.
I/O stream class.  Explain the hierarchy of Java I/O stream class.   Hierarchy of Java I/O streams Have a look at the following link: Java I/O
Java i/o
Java i/o   How can you improve Java I/O performance
output error
output error  this is my program import java.io.*; public class separate { public static void main(String[] args)throws IOException...]; for (k=0;k } } if i enter "my name" as the input the output
I/O to another applications
I/O to another applications  **What if there exists an application that needs a certain input and will give an output. Using Java, how can we invoke that application with an input and read the resulted output?**   Hi
i/o streamas
i/o streamas  java program using bufferedreader and bufferedwriter   Hi Friend, Try the following code: import java.io.*; class BufferedReaderAndBufferedWriter{ public static void main(String[] args) throws
Java I/O stream
Java I/O stream  What class allows you to read objects directly from a stream
Java I\O file
Java I\O file  What is the difference between the File and RandomAccessFile classes
Java I/O
Java I/O   What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy
I/O Java
I/O Java  import java.io.File; import java.io.FileNotFoundException... System.out.println(" Error in Concat:"+e); } } }   I am not really sure why... (FileNotFoundException e) { System.out.println(" Error: "+e + " "+ inputFile
java i/o operations
java i/o operations  how to write integer data to a file in java using random access file object or file writer or data outputstream i have already tried the write and writeInt methods....plz help
output of the program
output of the program  public static int sum(List list) { int sum = 0; for ( Iterator iter = list.iterator(); iter.hasNext(); ) { int i = ((Integer)iter.next()).intValue(); sum += i; } return sum
Java i/o opearations
Java i/o opearations  "FOLLOWING IS MY LAST QUESTION ON JAVA I/O... to a file in java using random access file object or file writer or data outputstream i..."),true)); for(int i=1;i<=10;i++){ System.out.print("Enter Number
find a substring by using I/O package
find a substring by using I/O package  Write a java program to find a sub string from given string by using I/O package
File I/O
File I/O  i am trying to read and write a file. my program works perfectly i am using PrintWriter and BufferedReader. but my problem is that when... a computer i am running linux i am of ubuntu output i want is: line1. i am
File I/O
File I/O  i am trying to write a program that reads a text file and writes it to another directory. the main purpose of this program is to take the text file then read it and write it into as a comma delimitade file. i have
File I/O
File I/O  greetings i was running into a problem. is their a way...(); File[] files = file.listFiles(filter); for (int i = 0; i < files.length; i++) { System.out.println("Processing " + files[i].getPath
File I/O
File I/O  i have a problem i am trying to print on a new line every time i reach a certain condition "if(line.startsWith("Creating"))" i want... this is my code package elite.tech.com; /*********** * program Cvs
Java I/O - Java Beginners
Creating Directory Java I/O  Hi, I wanted to know how to create a directory in Java I/O?  Hi, Creating directory with the help of Java.../java  yeah i konw tht method but i want another program whr we shld nt use
Java I/O Assistance + Loop
Java I/O Assistance + Loop  I'm trying to make this program write... and append all odd numbers 1-100 and finally close file. But for some reason I CANNOT Get the output as I want. I know where the error lays I just can't seem
Java I/O Byte Streams
Java I/O Byte Streams In this section we will discussed the I/O Byte Streams. This Stream handles the 8-bit binary input/output of data. Byte streams... I/O raw binary data the byte stream classes are defined. For all of the byte
Java I/O Character Streams
is used for output (write to). To work with the file I/O specialized classes...Java I/O Character Streams In this section we will discuss the I/O Character... and for this Java provides the Character stream I/O. Character stream I/O
Java I/O
JAVA I/O Introduction The Java Input/Output (I/O) is a part of java.io package... that support  input and output operations. The classes in the package are primarily... allow bytes to be read from and written to files or other input and output
output error - JSP-Servlet
output error  /*hi friends, the given below is my servlet program error? How can i solve this problem? */ HTTP Status 500... report message description The server encountered an internal error
Error output - JSP-Servlet
Error output  Can anyone please assist me; The printed output should be: The product is 10. But instead of it I got; The product is undefined. Can anyone trace what went wrong of my code pls
java i/o - Java Beginners
java i/o  Dear sir, i wrote a program where program asks "Enter your text:" then that text gets saved in a file called "data.txt" and then program gets closed. when i open the program again and enter text in this case previous
java i/o - Java Beginners
java i/o  thnx alot sir that this code helped me much in my program... so that i could write it line by line such as- Hello Java in roseindia Hello... in roseindia"); //Close the output stream out.close(); }catch (Exception e){//Catch
Java I/O From the Command Line
Java I/O From the Command Line In this section we will learn about the I/O... Streams. In this way an input is taken using the keyboard and output is written... be gotten using System.in Standard Output : Standard Output can be gotten
Java I/O Buffered Streams
Java I/O Buffered Streams In this section we will discuss the I/O Buffered Streams. In Java programming when we are doing an input and output operation then we are trying to interact our Java program to read from or write data
File I/O - Java Beginners
File I/O  Suppose a text file has 10 lines.How do I retrieve... oi oiu 25 ewr ytro 9+ po I want to retrieve 'abc' 'fg' .... 'yt' 'ewr...(IOException ioe) { System.out.println("ERROR::" + ioe.getMessage
File I/O - Java Beginners
File I/O  How to search for a specific word in a text file in java?  Hi Arnab, Please check the following code...) { System.out.println("ERROR::" + ioe.getMessage
Java I/O Data Streams
Java I/O Data Streams In this tutorial we will discuss the Java I/O Data Streams. To deal with the binary I/O of primitive data type values as well... your application to write the Java primitive data type values to the output
Classes and Interfaces of the I/O Streams
Classes and Interfaces of the I/O Streams   .... InterruptedIOException When the I/O operations to interrupted from any causes... then it occurs. IOException When the I/O operations to be failed
Text File I/O - DVD.java - Java Beginners
Text File I/O - DVD.java  NEED HELP PLEASE. The application should... the array to recreate the file. Here is my code but I need to modify it to the specifications on top. I don't know where to begin. Thanks. //package dvd
Creating a File I/O using import scanner, io.* and text.*
Creating a File I/O using import scanner, io.* and text.*  open a file for reading and open another file for writing data. input file hours-int, hourly rate-double, name-string. output file name-string, hours-int, hourly rate
Shortest the program as possible but output will not change
Shortest the program as possible but output will not change  #include...; } } int product(int m, int n){ int sum; int i; sum = 0; for(i = 0; i<n; i++){ sum = sum + m; } return sum; } void jw_insertion_sort ( void
Shortest the program as possible but output will not change
Shortest the program as possible but output will not change  #include...; } } int product(int m, int n){ int sum; int i; sum = 0; for(i = 0; i<n; i++){ sum = sum + m; } return sum; } void jw_insertion_sort ( void
why the program is showing error?
why the program is showing error?  <%@page import="java.sql.*"%>...=Integer.parseInt(rs1.getString(10)); 36: i=i+k; An error occurred at line..."); Integer i=0; out.println("hi"); while(rs1.next
Program error - WebSevices
Program error  Hello, Any one know the sample program for Login page using zend framework. Then how i connect my databse file to zend framework. Anyone help me
ERRor in executing DB program
ERRor in executing DB program  While executing following code an Error was generated.can any one help me for this. LiveDB liveDBObj... = liveDBObj.getPreparedStatement(qry); pstmt.setDouble(1,2.0); pstmt.setString(2,"name1"); int i
Program error - WebSevices
How i store my username, password values in my database using Zend Framework. In which library file i include the top of my program.... Any one help me...Program error  Hello friends, Username
Program error - WebSevices
Program error  Dear all, How i insert checkbox values into my database without using array In PHP . Anyone know the code