使用列表中的给定元素查找最近的元素,而不使用数组

时间:2014-10-29 08:08:06

标签: java

我有一个程序来获取给定值之前的最后一个值。我这样写:

while (rs.next()) {
                int temp = rs.getInt("alarmType");
                double fuel = rs.getDouble("nhienLieu");
                if(temp != 60 ){
                    alarmType = temp;
                        double currentValue = rs.getDouble("fuelLevel");
                        double changeValue = lastValue == 0 ? 0 : currentValue + fuel - lastValue;
                        lastValue = currentValue;
                        reportFuel = new FuelData(
                                rs.getString("accountID"),
                                rs.getString("deviceID"), 
                                rs.getInt("timestamp"),
                                rs.getDouble("latitude"),
                                rs.getDouble("longitude"), 
                                rs.getString("address"),
                                currentValue,
                                rs.getDouble("odometerKM"),
                                rs.getInt("status"),
                                changeValue,
                                alarmType,
                                rs.getDouble("nhienLieu"));
                        list.add(reportFuel);
                        if(fuel > 0){
                            changeValue = fuel;
                    }
                }
            }

在这段代码中,我使用临时变量temp来分配alarmType的值,然后我检查temp是否不等于60我打印它之前的值(temp = 60)(只有一个)最近的值)。但是,我的代码似乎打印满足此条件的所有值。那么如何在不使用数组的情况下只获得最接近temp = 60的一个值?

2 个答案:

答案 0 :(得分:1)

你去吧 基于示例1, 2, 3, 2, 4, 5, 3, 2

int current = -1, prev = -1;
    int data[] = { 1, 2, 3, 2, 4, 5, 3, 2 };

    for (int d = 0; d < data.length; d++) {
        current = data[d];

        if (current != 2) {
            prev = current;
        }

        if (current == 2 && prev != -1) {
            System.out.print(prev);
        }
    }// while loop

输出:1 3 3

只需用while(rs.next())

替换for循环

并将current = data[d];替换为current = rs.getInt("alarmType");

最后,用60替换2

答案 1 :(得分:0)

如果我理解正确,这将对您有所帮助:

FuelData tempFD = null;
while(rs.next()){
  int temp = rs.getInt("alarmType");

  if(temp == 60 ){
     //print or add to list tempFD
     tempFD = null; 
  } else {
     tempFD = new FuelData();
  }

}