Assuming that you have to write a method that, given a text file in the above format, a name and two dates, returns the total hours attributed to that person between the two dates, your code can be made very simple:
public int totalHours(Iterable<String> input, String person, String date1, String date2) {
SimpleDateFormat sdf = new SimpleDateFormat("MM.dd.yyyy");
Date start = sdf.parse(date1);
Date end = sdf.parse(date2);
int total = 0;
for (String line : input) { // assuming each string in input is a line
String parts[] = line.split(" ");
if ( ! parts[0].equals(person)) continue; // ignore - not him
Date d = sdf.parse(parts[1]);
if (d.compareTo(end) > 0) break; // if dates are sorted, we're finished
if (d.compareTo(start) <= 0) total += Integer.parseInt(parts[2]);
}
return total;
}
This code assumes that your input is already split into lines. You write that you already know how to read from files, so this should not be an obstacle. The function would run a lot faster (for repeated queries) if you store all lines in a TreeMap
, indexed by their dates. And even more efficient if you built a HashMap<String, TreeMap<Date, Integer> >
from the file, where the strings would be people's names and the integers would be the hours on those dates.
Edit: one way of doing the file-reading part
There are many ways of reading files. The most standard is the one you describe in your comment. This is a modified version that makes minimal changes to the above totalHours
(argument input
is now an Iterable<String>
instead of String[]
). The code has been adapted from
Iterating over the content of a text file line by line - is there a best practice? (vs. PMD's AssignmentInOperand):
public class IterableReader implements Iterable<String> {
private BufferedReader r;
public IterableReader(String fileName) throws IOException {
r = new BufferedReader(new FileReader(fileName));
}
public Iterator<String> iterator() {
return new Iterator<String>() {
String nextLine = readAndIfNullClose();
private String readAndIfNullClose() {
try {
String line = r.readLine();
if (line == null) r.close();
return line;
} catch (IOException e) {
return null;
}
}
@Override
public boolean hasNext() {
return nextLine != null;
}
@Override
public String next() {
String line = nextLine;
nextLine = readAndIfNullClose();
return line;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
}
And you should now be able to call it as follows:
System.out.println("Hours worked by Bob from 11.5.2015 to 15.5.2015: "
+ totalHours(new IterableReader("inputfile.txt"),
"Bob", "11.5.2015", "15.5.2015"));