簡體   English   中英

Java什么數據結構?

[英]Java what data structure?

我有一個像這樣的文件

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

我嘗試了堆棧以便從文件末尾開始搜索,但是在某些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應該為空,以便繼續其他行(最后,第二倒數等)。

我能做什么?

使用Map<String, String> 條形碼是地圖中的鍵:

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

 map.put( barcode, line );

使用普通循環逐行讀取文件。

您可以將數據存儲在數組中,並使用兩個嵌套循環。 這不是最有效的方法,但可能是最簡單的方法。 例:

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
    }
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM