1

次のような行を含むファイルがあります

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

しかし、私が言ったように、これは正しいアプローチではありません。スタックが空になるからです。行ごとに検索したいのですが、他の行 (最後、最後から 2 番目など) を続行するには、STRUCTURE を空にする必要があります。

私に何ができる?

4

2 に答える 2

0

を使用しMap<String, String>ます。バーコードはマップのキーです。

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

 map.put( barcode, line );

通常のループを使用して、ファイルを 1 行ずつ読み取ります。

于 2013-05-28T08:22:43.177 に答える
0

データを配列に格納し、ネストされた 2 つのループを操作できます。これは最も効率的な方法ではありませんが、おそらく最も簡単な方法です。例:

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
    }
  }
}
于 2013-05-28T08:28:53.407 に答える