java - 更新所有三个项目后运行 if 条件

标签 java if-statement

我有一个列表,它应该定期从多个主机接收值并对这些值进行一些操作。

List<Integer> loadList = new ArrayList<>(3);
if ((dstIp.toString().equals("10.0.0.1")
                        && udp.getPayload() != null) {

                    loadList.add(0, intLoad1);
                }
                else if ((dstIp.toString().equals("10.0.0.2") 
                        && udp.getPayload() != null) {

                    loadList.add(1, intLoad2);
                }
                else if ((dstIp.toString().equals("10.0.0.3") 
                        && udp.getPayload() != null) {

                    loadList.add(2, intLoad3);
                }

                if (!loadList.isEmpty() && !loadList.contains(null)) {
                    int sum = loadList.stream().mapToInt(Integer::intValue).sum();
                    System.out.println("---- Sum: "+sum);
                    double averageLoad = ((double) sum) / loadList.size();
                }

在我的代码中,第四个 if 条件(我的意思是 if (!loadList.isEmpty() && !loadList.contains(null)))每次都会运行收到一个新值,但我试图更改它,以便它将在每个周期结束后运行(当列表中的所有三个元素都更新时)。我的意思是我希望它仅在收到所有三个负载值时才运行(以便我找到新收到的值的平均值)。

我寻找解决方案,但没有找到任何东西。可能吗?

最佳答案

您可以添加三个 boolean 字段并在最后一个 if 语句中使用它们:

boolean first = false;
boolean second= false;
boolean third = false;
List<Integer> loadList = new ArrayList<>(3);
if ((dstIp.toString().equals("10.0.0.1") && udp.getPayload() != null) {
    loadList.add(0, intLoad1);
    first = true;
} else if ((dstIp.toString().equals("10.0.0.2") && udp.getPayload() != null) {
    loadList.add(1, intLoad2);
    second = true;
} else if ((dstIp.toString().equals("10.0.0.3") && udp.getPayload() != null) {
    loadList.add(2, intLoad3);
    third = true;
}

if (!loadList.isEmpty() && !loadList.contains(null) && first && second && third) {
    int sum = loadList.stream().mapToInt(Integer::intValue).sum();
    System.out.println("---- Sum: "+sum);
    double averageLoad = ((double) sum) / loadList.size();
    first = false;
    second= false;
    third = false;
}

关于java - 更新所有三个项目后运行 if 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53381675/

相关文章:

c# - float 比双倍慢吗? 64位程序运行速度比32位程序快吗?

java - 如何设置“导航”和“当前 Activity ”的“返回”选项

java - 避免 if else 语句

java - BufferedReader 在从 USB 读取时跳过随机字符

java - 为什么尽管类是可序列化的,但HashMap的哈希表标记为 transient

if-statement - Gradle 仅在定义的属性上运行任务

java - 在 IF 条件中使用 NOT 运算符

linux - 执行 if...then...fi 时出现 Cygwin 错误 - Bash 脚本

javascript - 多条件语句 JavaScript

java - 改造如何打印响应 JSON