I have finally gotten my code to where it works. Although it isnt the easiest to read. I am reading from a text file that has
Date/time Tip from xxx
tip totalAmount
My code now takes the amount tipped by a person and adds them together. eg X tip 10, X tip 20, X tip 30, Y tip 200, Z tip 30, Z tip 40 and outputs
X=60
Y=200
Z=70
I did this by turning my Map< String,Integer> into an Object[] tipsPerPerson
So how would I go about sorting this Object[] tipsPerPerson into something a bit easier to read (theres over 2000 names) a bit like this
Y=200
Z=70
X=60
Here is a portion of the code that im stuck at
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;
public class Tip {
public static void main(String[] args)
{
int lineNumber = 1;
Map<String, Integer> tipsByName = new HashMap<String, Integer>();
String fileName = "C:\\Users\\David\\Desktop\\tips.txt";
System.out.println("Reading text from file");
try {
FileReader inputFile = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(inputFile);
String line;
String currentTipper = null;
while ((line = bufferedReader.readLine()) != null) {
if (lineNumber % 2 != 0) {
final String tipperName = line.substring(line.indexOf("from ") + 5);
currentTipper = tipperName;
} else {
final Integer tipValue = Integer.parseInt(line.substring(0, line.indexOf("\t")));
// here we store the tip in the map. If we have a record we sum, else
// we store as is
tipsByName.put(currentTipper, (tipsByName.get(currentTipper) == null ? 0 : tipsByName.get(currentTipper))
+ tipValue);
}
lineNumber++;
}
bufferedReader.close();
Object[] tipsName = tipsByName.entrySet().toArray();
for (int i = 0; i < tipsByName.size(); i++) {
System.out.println(tipsName[i]); // output the map
}
} catch (Exception e) {
System.out.println("Error while reading file line by line: " + e.getMessage());
}
}
}