1

I have a file with lines like

barcode date action

for example

IP720H7 20130527192802 in the box

and starting from the end of the file, i want to search for the previous line that contains exact the same barcode, and take its date and action.

i will give the example below

FILE

IP720H4 20130528131526  in refrigerator
IP720H4 20130528130526  in refrigerator         
IP720H2 20130528130547  in refrigerator         
20IB7   20130528130528  box             
IP720H4 20130528130530  in the box  

WANTED OUTPUT

IP720H4 20130528130530  in the box  FOUND  LAST IP720H4 20130528130526  in refrigerator
20IB7   20130528130528  box NOT FOUND
IP720H2 20130528130547  in refrigerator NOT FOUND
IP720H4 20130528130526  in refrigerator FOUND LAST  IP720H4 20130528131526  in refrigerator
IP720H4 20130528131526  in refrigerator NOT FOUND

I tried stack in order to start searching from the end of the file, but after some pop() stack gets empty.

while(!lifo.empty())
{
    String[] next_line = lifo.pop().toString().split(" ");

    //This is the abrcode of the next line
    String next_barcode = next_line[0].toString();

    //barcode is the one i am trying to find (last of the file)
    if (next_barcode.equals(barcode))
    {
        System.out.println(nnext_barcode + " found");
        break;
    }
    else
    {
        //NOT FOUND
    }
}

But as i said this is not the correct approach, cause the stack gets empty. I want to search line by line but the STRUCTURE should get empty, in order to continue with other lines (last, second last, etc).

What can i do?

MD Sayem Ahmed
  • 28,628
  • 27
  • 111
  • 178
tequilaras
  • 277
  • 3
  • 7
  • 15
  • 1
    The problem is not with the data structure but the method of reading in the file. – Adam Arold May 28 '13 at 08:19
  • 1
    possible duplicate of [Read a file line by line in reverse order](http://stackoverflow.com/questions/6011345/read-a-file-line-by-line-in-reverse-order) – Adam Arold May 28 '13 at 08:19

2 Answers2

0

Use a Map<String, String>. The barcode is the key in the map:

 String lastLine = map.get( barcode );
 if( null != lastLine ) {
     ... found previous line; do something with it ...
 }

 map.put( barcode, line );

Use a normal loop to read the file line by line.

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
0

You could store the data in an array and work with two nested loops. This is not the most efficient way but probably the simplest. Example:

String[] data;
// read input into data array

for (int i = data.length - 1; i >= 0; --i) { // begins with the last line and continues until first line
  String currentBarcode = getBarcode(data[i]);

  for (int j = i - 1; i >= 0; --j) { // begins with the line before current line and tests every line on same barcode
    if (getBarcode(data[j] == currentBarcode) {
      // print output
      break; // end search when barcode found
    }
  }
}
JMP
  • 81
  • 3