在我的代码的一部分中,我试图为MacAdress变量(dstMac
)赋值。我还有一个名为indexMax
的int变量,其值可以为0或1或2(将在我的程序中更改)。
现在我要尝试的是根据indexMax将值分配给dstMac。我的意思是,如果indexMax = 0,则dstMac = value0,如果indexMax = 1,则dstMac = value1,然后... (根据indexMax的值选择变量的名称)
MacAddress dstMac;
MacAddress value0 = MacAddress.of("00:00:00:00:00:01");
MacAddress value1 = MacAddress.of("00:00:00:00:00:02");
MacAddress value2 = MacAddress.of("00:00:00:00:00:11");
if (maxvalue > 50){
dstMac = value%d, indexMax // Just for showing what I'm trying to do, I know that this is wrong
}
我尝试了类似dstMac = String.format("value%d", indexMax);
之类的操作,但收到此错误:
Type mismatch: cannot convert from String to MacAddress
那我该怎么做?
答案 0 :(得分:0)
要实现此逻辑,可以使用某种结构来保存mac值,然后从中选择一个。只是一个示例:
List<MacAddress> addresses = Arrays.asList(value0, value1, value2);
MacAddress dstMac = Collections.min(addresses, new Comparator<MacAddress> {
public int compare(MacAddress a, MacAddress b) { // some custom logic to choose min mac address, for example
if (a > b)
return 1;
if (a == b)
return 0;
return -1;
}
});
或者您可以简单地对其进行迭代并返回第一个可接受的值:
List<MacAddress> addresses = Arrays.asList(value0, value1, value2);
MacAddress dstMac = selectOne(addresses);
....
MacAddress selectOne(List<MacAddress> addresses) {
for (MacAddress mac : addresses) {
if (some condition) {
return mac
}
}
return null; // if there is no acceptable mac address
}