【问题标题】:return statement in boolean method布尔方法中的返回语句
【发布时间】:2022-11-11 13:54:24
【问题描述】:

我不明白我应该返回什么。如果最后一次发生,我的方法返回 false 通过for循环它是错误的。如果最后一次为真,则返回真。但我希望它返回错误,无论错误发生在哪里。

    public class test {
        public static void main(String[] args) {
            int number = 4;
            int[] intArray = {4, 8, 12, 16};
            System.out.println(allMultipleOf(intArray, number));
        }
        public static boolean allMultipleOf(int[] ary, int n){
            boolean a = true;
            for(int i = 0; i < ary.length; i++){
                if(ary[i] % n == 0){
                    a = true;
                    //System.out.println(a);
                    break;
                } else {
                    a = false;
                }
            }
    }
        return a; //what should I return
}

【问题讨论】:

  • 一旦你第一次找到一个假案例,你就会返回假。如果您从未找到错误案例,请返回 true。您不需要abreak,您可以从循环内部返回。

标签: java methods boolean return


【解决方案1】:

您可以从方法中提前返回 false,如果我们到达末尾没有返回 false,则返回 true:

public static boolean allMultipleOf(int[] ary, int n) {
    for (int i = 0; i < ary.length; i++) {
        if (ary[i] % n != 0) {
            return false;
        }
    }
    return true;
}

【讨论】:

    【解决方案2】:

    它应该返回 false ,布尔值的默认值是在这个地方打印。

    您可以在方法中创建 return 语句。它返回真。

      public static boolean allMultipleOf(int[] ary, int n){
            boolean a = true;
            for(int i = 0; i < ary.length; i++){
                if(ary[i] % n == 0){
                    a = true;
                    //System.out.println(a);
                    break;
                } else {
                    a = false;
                }
            } 
       return a; 
    }
        
    

    }

    【讨论】:

      猜你喜欢
      • 2013-10-01
      • 1970-01-01
      • 2015-05-03
      • 2012-08-16
      • 2021-09-27
      • 1970-01-01
      • 1970-01-01
      • 2013-12-12
      • 2016-11-08
      相关资源
      最近更新 更多