有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (3) 个答案

  1. # 1 楼答案

    您可能必须这样实现

    int[] arr = new int[] { 1, 2, 3, 4, 5 };
    
    public boolean legal(int total){
        int i=0;
        int sum=0;
        while (i < arr.length) {
           sum += arr[i];
           i=i+1;
        } 
        if(sum <= total){
           return true;
        }
        else{
          return false;
        }
    }
    
  2. # 2 楼答案

    使用Java 8streams

    public boolean legal(int total) {
        return numbers.stream()
         .mapToInt(Integer::intValue) // converts the stream to an IntStream object
         .sum() <= total; 
    }
    
  3. # 3 楼答案

    循环列表的最简单方法可能是使用foreach循环

    public boolean legal(int total) {
    
        int sum = 0;
        for(int num : numbers) { //loop through every number in ArrayList numbers
            sum += num;  
        }
    
        return sum <= total; //return true if the sum is less than or equal to total
    }
    

    foreach循环比for循环更容易使用,因为您不需要处理索引。但是,只有当集合具有索引时,才能使用foreach循环,对于您的情况,ArrayList具有索引。因此,foreach循环是在列表中循环的最简单方法

    如果您的集合没有索引(如果您使用例如Set),则可以使用常规的for loopIterator