我有一个程序来获取给定值之前的最后一个值。我这样写:
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
的一个值?
答案 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())
并将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();
}
}