I am creating methods that will extract info out of a text file.

The program is for a real estate office manager who needs to run reports on property listings.

The text file will contain property number, property type, price, and agent id as follows.

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 txt file is space delimitted.

need to store each property type in a set
and use a Map to calculate total property listed in dollars and cents for each agent id.

I was able to extract the property type to a TreeSet using

in.useDelimiter("[^a-zA-Z]+");

I am having a hard time with the numbers.

Using this method:

private static TreeSet<String> getAgentID(String filename) throws FileNotFoundException {
		TreeSet<String> agentID = new TreeSet<String>();
		Scanner in = new Scanner(new File(filename));
		
		while (in.hasNextLine())
	    {
	       String agentNum = in.nextLine();
	       String sub = agentNum.substring(agentNum.length() - 4, agentNum.length());
			agentID.add(sub);        
	    }
	    return agentID;

	}

I have parsed out the agent ID for the TreeSet, but I also have Property Price and Property ID number.

Here is my code so far. I tried to bring in the file and output it to a new file with line breaks after each word, but its not saving all the items.

What would be your strategy for parsing this text file without changing the original text file?

My code so far:

/**
 * 
 */
package com.wgu.aat1.task2.weigand.ken.sandbox;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeSet;




/**
 * @author Owner
 *
 */
public class AgentReport {

	/**
	 * @param args
	 * @throws FileNotFoundException 
	 */
	
	
	public static void main(String[] args) throws FileNotFoundException {
		
		/* TODO 
		 * 1) Prompt the user for the name 
		 * of the input file (listings.txt).
		 */
		
		Scanner in = new Scanner(System.in);
		System.out.print("Enter input filename (ex: listings.txt): ");
		String fileName = in.nextLine();
		
		/* TODO
		 * 2) Use an unbuffered file input stream 
		 * to open listings.txt file and read 
		 * in property listings.
		 */
		 Scanner sc2 = null;
		    try {
		        sc2 = new Scanner(new File(fileName));
		    } catch (FileNotFoundException e) {
		        e.printStackTrace();  
		    }
		    
		    PrintWriter out = new PrintWriter("readfile.txt");
		    while (sc2.hasNextLine()) {
		            Scanner s2 = new Scanner(sc2.next());
		            
		        @SuppressWarnings("unused")
				boolean b;
		        while (b = s2.hasNext()) {
		            String s = s2.next();
		            System.out.println(s);
		            
		            out.println(s);
		            
		        }
		        in.close();
		        out.close();
		        
		    }
		
		
		
		
		/* TODO
		 * 4) Store each property type into a Set.
		 * 		TreeSet sorts alphabetically
		 */
		TreeSet<String> propertyTypes =	getPropertyTypes(fileName);
		TreeSet<String> propertyListedAgentIDs =	getAgentID(fileName);
		
		Iterator<String> iter = propertyTypes.iterator();
		while (iter.hasNext())
		{
		   String propertyType = iter.next();
		   System.out.println(propertyType);
		}
		
		Iterator<String> iter2 = propertyListedAgentIDs.iterator();
		while (iter2.hasNext())
		{
		   String agentID = iter2.next();
		   System.out.println(agentID);
		}
		/* TODO
		 * 6) Use a Map to calculate total property
		 * listed in dollars and cents for each agent id.
		 *  Agent id would be the key
		 *  accumulated total of property listed equals value
		 */
		Map<String, Double> propertyTotals;
		/* TODO
		 * 7) Sort map by agent ID
		 */
		
		/* TODO
		 * 7) Create an agentreport.txt file.
		 */
		
		
		/* TODO
		 * 7) Use an Iterator to iterate through your Set 
		 * and write your sorted set of property types sold 
		 * by the agents to the agentreport.txt file 
		 * using unbuffered file output stream.
		 */
		

	}
	
	private static TreeSet<String> getAgentID(String filename) throws FileNotFoundException {
		TreeSet<String> agentID = new TreeSet<String>();
		Scanner in = new Scanner(new File(filename));
		
		while (in.hasNextLine())
	    {
	       String agentNum = in.nextLine();
	       String sub = agentNum.substring(agentNum.length() - 4, agentNum.length());
			agentID.add(sub);        
	    }
	    return agentID;

	}

	/* DONE
	 * 3) Convert property type to upper case
	 * (use methods from string class)
	 */
	/**
    Reads all words from a file.
    @param filename the name of the file
    @return a set with all UPPERCASE words in the file. Here, a 
    word is a sequence of upper and lowercase letters.
 */
 public static TreeSet<String> getPropertyTypes(String filename)
    throws FileNotFoundException
 {
    TreeSet<String> words = new TreeSet<String>();
    Scanner in = new Scanner(new File(filename));
    // Use any characters other than a-z or A-Z as delimiters
    in.useDelimiter("[^a-zA-Z]+");
    while (in.hasNext())
    {
       words.add(in.next().toUpperCase());        
    }
    return words;
 }
 

	
}

A simpler approach would be to parse out an object (let's say for example PropertyInfo object) from each line in the file and then do the processing rather than parsing the file multiple times and searching for selective information.

Steps:

  1. For each line in the file
  2. Read the line and split it based on the separator (comma or spaces)
  3. The array returned by split will contain property number, property type, price, and agent id as string
  4. Create a new PropertyInfo object by passing in the four pieces of information e.g. PropertyInfo p = new PropertyInfo(propertyNumber, type, price, id)
  5. After the entire file has been read, you should have a list of PropertyInfo objects.

Now any sort of reporting is as simple as iterating over the PropertyInfo list/collection and retrieving relevant information. This also has the advantage of easing your job in case you need to report some other statistic related to the property information. For e.g. to get the set of agent ids, you can simply do:

final List<PropertyInfo> properties = parsePropertiesFromFile(fileObj);
final Set<String> set = new HashSet<String>(properties.size());
for (final PropertyInfo property : properties) {
    set.add(property.getAgentId());
}
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.