【问题标题】:When comparing array elements of two arrays, boolean result always returns true比较两个数组的数组元素时,布尔结果总是返回真
【发布时间】:2014-03-01 00:26:57
【问题描述】:

比较两个 int 数组中的元素时遇到问题。我正在使用 for 循环来比较两个数组中的每个元素,如果元素匹配,则布尔结果返回 true,否则返回 false。问题是它总是返回 true,不管它们是否匹配。

整个程序在这里http://pastebin.ca/2626244

循环:

    boolean result;
    int counter = 0;
    //compares answers[] to key[]
    for (int i = 0; i < size; i++)  {
        if (answers[i] == key[i]) {
            result = true; 
            }
        if (answers[i] != key[i]) {
            result = false;
        }
        if (result = true) {
            counter++;
        }
    }
    System.out.println(counter+"/"+size+" questions are correct.");

因此,“计数器”始终与元素总数(“大小”)相同。即使两个数组包含完全不同的值,结果仍然不会是 0/size。它似乎总是大小/大小。

我是否错误地比较了数组(请参阅完整程序),还是我的循环有问题?

【问题讨论】:

    标签: java arrays boolean


    【解决方案1】:

    使用比较运算符== 比较事物,而不是赋值运算符=。但是因为result 已经是boolean,所以只需使用boolean 本身。

    改变

    if (result = true) {
    

    if (result)
    

    【讨论】:

    • 非常感谢!!这使得 int 计数器现在可以正常工作。为什么这行得通?但是,“如果(结果)”是一个有效的陈述吗?
    • if 语句需要的表达式类型是boolean,而您已经有了boolean。如果你真的想要,你可以说if (result == true),但它很冗长,需要进行不必要的比较。
    【解决方案2】:
    = is use to assign the value and to compare the value use `==`
    

    所以需要修改下面的代码:

    if (result == true) {
        counter++;
    }
    

    或更好的解决方案是

    if (result) {
        counter++;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-19
      • 1970-01-01
      • 2018-03-24
      相关资源
      最近更新 更多