计数数字在数组中可被10整除

时间:2017-02-16 04:14:26

标签: java arrays methods

我得到了一个赋值,它让我创建了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();
}

2 个答案:

答案 0 :(得分:5)

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

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());

答案 1 :(得分:0)

你可以这样做。传递完整数组,然后检查除以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;        
}