我有一个像
这样的行的文件barcode date action
例如
IP720H7 20130527192802 in the box
从文件末尾开始,我想搜索包含完全相同条形码的上一行,并查看其日期和操作。
我将举例如下
文件
IP720H4 20130528131526 in refrigerator
IP720H4 20130528130526 in refrigerator
IP720H2 20130528130547 in refrigerator
20IB7 20130528130528 box
IP720H4 20130528130530 in the box
通缉输出
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
我尝试使用stack来从文件的末尾开始搜索,但是在一些pop()堆栈变空之后。
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
}
}
但正如我所说,这不是正确的方法,导致堆栈变空。我想逐行搜索,但STRUCTURE应该为空,以便继续使用其他行(last,second last等)。
我该怎么办?
答案 0 :(得分:0)
使用Map<String, String>
。条形码是地图中的关键:
String lastLine = map.get( barcode );
if( null != lastLine ) {
... found previous line; do something with it ...
}
map.put( barcode, line );
使用普通循环逐行读取文件。
答案 1 :(得分:0)
您可以将数据存储在数组中并使用两个嵌套循环。这不是最有效的方法,但可能是最简单的方法。例如:
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
}
}
}