【问题标题】:this java code isn't functioning correctly [closed]此 java 代码无法正常运行 [关闭]
【发布时间】:2021-11-07 22:09:21
【问题描述】:

这是一个数组过滤器,当参数满足时返回 1,当参数不满足时返回 0。对于参数,当 9 存在时 11 也必须存在 & 当数组中存在 7 时 13 一定不存在。

即使 9 和 11 存在并且 7 存在但 13 不存在,我的代码也会返回 0。有人可以看看吗?

public class Question4 {
    private int [] array = {1,2,3,4,9,11,7};
    private boolean condition1 = true;
    private boolean condition2 = true;
    
    public int isFilter() {
        //condition 1 : (if list contains 9 then it must contain 11)
        for (int i = 0; i < array.length; i++) {
            if (array[i] == 9) {
                for (int j = 0; j < array.length; j++) {
                    if (array[j] == 11) {
                        condition1 = true;
                    }
                    else {
                        condition1 = false;
                    }
                }
            }
        }
        
        //condition 2 : (if list contains 7 then it must not contain 13)
        for (int k = 0; k < array.length; k++) {
            if (array[k] == 7) {
                for (int l = 0; l < array.length; l++) {
                    if (array[l] == 13) {
                        condition2 = false;
                    }
                    else {
                        condition2 = true;
                    }
                }
            }
        }
    
        //Evaluation and Return
        if (condition1 == true && condition2 == true) {
            return 1;
        }
        else {
            return 0;
        }
    }
}

【问题讨论】:

  • 那么...你知道如何debug一个程序吗?
  • @MarsAtomic 不,我一般是编程初学者。
  • 我发现我需要 break 语句才能使其工作。谢谢大家帮助我。

标签: java arrays if-statement return boolean


【解决方案1】:

因为这是家庭作业,所以我将笼统地回答,而不是用“代码”。

您的主要问题是您的代码难以阅读;你最好的第一步是重构:

创建一个这样的方法:

private static boolean contains(int[] array, int i) {
    // write your own implementation here that returns true if array contains i
}

用它来重写你的条件,例如:

if (contains(array, 7) && contains(array, 13)) {
    // broken rule - do something
}

做完之后应该是易写易读。

【讨论】:

  • 类名漏掉了哈,谢谢下次写代码的时候注意一下。
【解决方案2】:

代替

private boolean condition1 = true;
private boolean condition2 = true;

使用

 private boolean condition1 = false;
 private boolean condition2 = false;

【讨论】:

  • 抱歉,这对我不起作用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-25
  • 1970-01-01
  • 2017-02-08
  • 2011-12-16
  • 1970-01-01
  • 2016-03-28
相关资源
最近更新 更多