-3

I will write data into the text file in format like this:

Jonathan 09.5.2015 1 
John 10.5.2015 4 
Jonathan 11.5.2015 14 
Jonathan 12.5.2015 15 
Jonathan 13.5.2015 7 
Tobias 14.5.2015 9 
Jonathan 15.5.2015 6 

The last number is hours. I need to make something where I can write two dates and name. For example - Jonathan 11.5.2015 and second date 15.5.2015. All I want to do is count hours between these dates. Output should looks like Jonathan 11.5.2014 - 15.5.2014 - 42 hours I don't have problem with GUI but I don't know the right way how to compute my result.

Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102
Kym
  • 13
  • 4
  • Oh sorry.. I forgot to mark the code. I have made GUI and writing datas into the text file via FileWriter. I can also read text file. But i dont know how to work with it. – Kym May 18 '15 at 19:40
  • This question fundamentally doesn't make sense: how does `11.5.2014 - 15.5.2014` relate to `42 hours`? You don't specify how one date relates to another, or even what format it's in. You make it unclear whether you're comparing any two lines in the file, or if *one* line has to have two dates in it? Is the file format above for the input, the output or both? You need more well-crafted examples. Check http://www.sscce.org – Nathaniel Ford May 21 '15 at 16:39
  • Will the dates always be in increasing order? Are you always returning the sum of all hours for the requested person between (or at) the two dates?. This simplifies things a lot. – tucuxi May 21 '15 at 17:02

2 Answers2

1

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")); 
Community
  • 1
  • 1
tucuxi
  • 17,561
  • 2
  • 43
  • 74
  • If the answer is correct & helpful, you should upvote and/or accept it – tucuxi May 22 '15 at 20:38
  • Ofcourse. Also I have few questions.. Is this correct way how to acces file? String filename = "databaze.txt"; try{ FileReader filetoread = new FileReader(filename); BufferedReader bf = new BufferedReader(filetoread); }catch(IOException e){ System.out.println("error"); } Your methos uses arrray as file input.. that means that i should make array from file? One array index for one line in txt file? edit: how to format code here? I found guides but every guide telling me to click {} symbol below... but i cant see anything... Sorry... – Kym May 22 '15 at 21:16
  • See the edited version. If it seems too complicated, pass the result of `Files.readAllLines(FileSystems.getDefault().getPath(fileName), Charset.defaultCharset());` instead the `new IterableReader(fileName)` – tucuxi May 23 '15 at 09:04
  • Thank you for doing this for me :) ! Also it throwing error on line "Date d = sdf.parse(line[1]);" error - array required but String found.. and I have little bit problems with impementing this to my code.. Its long time I used java last time... Sorry for bothering you.. – Kym May 23 '15 at 10:29
  • Thanks... can you help me please implement it to my code? My app have 1 window when you will set name and 2 dates and then you will click Output button and new window will be opened. The new window will write result. http://pastebin.com/hUa4rKW3 first window with Output botton http://pastebin.com/dA9cJ8Yw second widow with result... where should i put your code ? :/ – Kym May 23 '15 at 11:31
  • Oh god... I am lost.. Please... can you make me working example in java? I need something working to see how its actually working.. – Kym May 23 '15 at 15:07
  • Ask it as a new question, providing as many details as possible. This time I won't be able to help. – tucuxi May 23 '15 at 16:24
  • I have to wait few days... I cant write question right now.. :( – Kym May 23 '15 at 17:41
0
 import java.io.*;
    class Test{
        BufferedReader f = null;
        try{
            f = new BufferedReader(new FileReader("youFile.txt"));
            String something=null;
            while((something=f.readLine())!=null){
                String[] part= something.split(" ");
            }
        }catch(FileNotFoundException e){
                e.getMessage();
        }
    }

After you split this code, you will get a array "part" with 3 index per line, so you should convert to int or String depending what you want to do. 0 = name 1 = hour 2 = this forever alone number :D