【问题标题】:Counting number divisible by 10 in an array计算数组中可被 10 整除的数字
【发布时间】:2017-07-05 00:36:20
【问题描述】:

我被分配了一个任务,让我创建了 3 个方法,这些方法创建了一个数组、打印一个数组并计算数组中所有可被 10 整除的数字。给我最麻烦的部分是计算能被 10 整除的数字。这是我到目前为止的代码:

public int[] createArray(int size) {

    Random rnd = new Random();
    int[] array = new int[size];

    for (int i = 0; i < array.length; i++) {
        array[i] = rnd.nextInt(101);
    }
    return array; 
}

public void printArray() {

    Journal5a call = new Journal5a();
    int[] myArray = call.createArray(10);

    for (int i = 0; i < myArray.length; i++) {
        System.out.println(myArray[i]);
    }
    System.out.println("There are " + call.divideByTen(myArray[i]) + " numbers that are divisable by 10");
}

public int divideByTen(int num) {

    int count = 0;

    if (num % 10 == 0) {
        count++;
    }
    return count;        
}

public static void main(String[] args) {

    Journal5a call = new Journal5a();
    Random rnd = new Random();

    call.printArray();
}

【问题讨论】:

  • 传入整个数组。然后遍历它并调用你的 if 条件并返回最终计数。
  • 传递完整数组,而不是单个元素
  • System.out.println("There are " + call.divideByTen(myArray[i]) + " numbers that are divisable by 10"); i 超出范围。

标签: java arrays methods


【解决方案1】:

将数组传递给方法,并使用它来确定计数。你的算法看起来很合理。比如,

public int divideByTen(int[] nums) {
    int count = 0;
    for (int num : nums) {
        if (num % 10 == 0) {
            count++;
        }
    }
    return count;
}

,在 Java 8+ 中,使用 IntStreamfilter 类似

return (int) IntStream.of(nums).filter(x -> x % 10 == 0).count();

那你可以这样称呼它

System.out.println("There are " + call.divideByTen(myArray) 
        + " numbers that are divisible by 10");

printf 和内联类似

System.out.printf("There are %d numbers that are divisible by 10.%n", 
        IntStream.of(nums).filter(x -> x % 10 == 0).count());

【讨论】:

  • 另外,您可以在打印数字的循环中添加total += call.divideByTen(myArray[i]);,然后打印total,尽管需要一个新变量。
【解决方案2】:

你可以这样做。传递完整的数组,然后检查除以 10。为简单起见,跳过了其他部分。

public void printArray() {

    Journal5a call = new Journal5a();
    int[] myArray = call.createArray(10);

    divideByTen(myArray);
}

public int divideByTen(int[] num) {

    int count = 0;
    for(i=0;i<num.length;i++)
    {
        if (num[i] % 10 == 0) {
            count++;
        }
    }
    return count;        
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-06
    • 2013-05-12
    相关资源
    最近更新 更多