Reading line from a file, and manipulating individual words from each line?
I am attempting to the read-in a .txt file and create a map to calculate total property listed in dollars and cents for each agent id. The agent ids are the three digit numbers at the end of开发者_如何学JAVA each line. The problem is, I'm not exactly sure how to go about doing this.
I'm thinking I should create a while loop and add each line to an arraylist, and then..... I'm lost.
110001 commercial 500000.00 101
110223 residential 100000.00 101
110333 land 30000.00 105
110442 farm 200000.00 106
110421 land 40000.00 107
112352 residential 250000.00 110
Ok, I know It has been a long time since I started this thread, but I haven't been able to revisit this problem for weeks now. (I'm attempting to learn this for personal growth, so it hasn't been priority) So far I have come this far...
My method for creating the map is this:
public void createMap()
{
if(in != null)
{
while(in.hasNextLine())
{
String s = in.nextLine().trim();
System.out.print(s);
String[] p = s.split(" ");
String agentId = p[3];
double property = Double.valueOf(p[2]);
if(!map.containsKey(agentId)){
//if not then add the new key with new value
map.put(agentId, property);
in.nextLine();
}
else
{ //if key is present, add the value..
map.put(agentId, map.get(agentId) + property);
in.nextLine();
}
}
}
}
Then in my program that I am running: I convert map to a Set and using a enhanced for-loop print each key and value.
Set<String> keySet = examp.map.keySet();
for (String key : keySet)
{
double value = examp.map.get(key);
System.out.println(key + "->" + value);
}
my output however gives me this: {} "empty brackets"! What am I doing wrong?
After you've read in your data from the file these options might be the simplest means of parsing the strings.
This is the built in Java way of parsing a string. http://download-llnw.oracle.com/javase/6/docs/api/java/lang/String.html#split(java.lang.String)
This is an old legacy way of parsing strings in Java but still valid. http://download.oracle.com/javase/6/docs/api/java/util/StringTokenizer.html
Implementation example using StringTokenizer. http://www.mkyong.com/java/java-stringtokenizer-example/
Like other commentors have said, just try experimenting. When you're a beginner the best way to learn is by getting your hands dirty. Of course you'll make mistakes and throw away code but you'll learn a lot in the process.
If you have it in an arraylist, you could do something like:
HashMap<String, Integer> result = new HashMap<String, Integer>(); //<agent id, amount>
for(String line: arraylist)
{
String[] items = line.split(" ");
String agent = items[3];
double amount = Double.valueOf(items[2]);
if(!result.containsKey(agent)
result.put(agent, amount);
else
result.put(agent, result.get(agent) + amount);
}
You can iterate over the hash map's keys to get the results.
I would rather not spoil your fun by coding the whole thing. But I would advise starting out by breaking this into functions, and deciding what you want each function to do.
For instance, it would be nice to have a function like this:
Map<String, java.math.BigDecimal> calculatePropertyAmounts(List<String> lines)
and it would be nice to have a function that would get the property amount from a line, like this:
java.math.BigDecimal readAmountFromLine(String line)
and likewise
String readAgentIdFromLine(String line)
and maybe something like
List<String> readLinesFromFile(String filename)
I've missed some bits obviously but that's the general idea. Once you have broken it up in pieces you can conquer the pieces individually, then assemble a solution out of them.
Open File:
String pFile = "input.txt"; BufferedReader in; try { in = new BufferedReader(new FileReader(pFile)); } catch (FileNotFoundException ex) { System.out.println("File Not Found"); return; }
Declare the HashMap:
HashMap<String, Double> map = new HashMap<String, Double>(); //<agent id, amount>
Read lines, Parse them and add to Hash-Map:
String line; //loop till end of file while((line = in.readLine()) != null) { //remove spaces from front and back... line = line.trim(); //ignore if line is empty if(line.isEmpty()) continue; //split line into array String[] p=line.split(" "); //now according to your input-file's first line //p[0]="110001" //p[1]="commercial" //p[2]="500000.00" //p[3]="101" //so do whatever you want. String agentId = p[3]; //Parse the string to double. double property = Double.valueOf(p[2]); //Check if hash already contains key. if(!map.containsKey(agentId)) //if not then add the new key with new value map.put(agentId, property); else //if key is present, add the value.. map.put(agentId, map.get(agentId) + property); }
精彩评论