Java 数组中可被10整除的数的计数

Java 数组中可被10整除的数的计数,java,arrays,methods,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++) {

我被分配了一个任务,让我创建了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();
}
public int[]createArray(int size){
随机rnd=新随机();
int[]数组=新的int[size];
for(int i=0;i
将数组传递给该方法,并使用该数组确定计数。你的算法看起来很合理。大概

public int divideByTen(int[] nums) {
    int count = 0;
    for (int num : nums) {
        if (num % 10 == 0) {
            count++;
        }
    }
    return count;
}
在Java 8+中,使用
IntStream
过滤器

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

你可以这样做。通过完整数组,然后检查是否除以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;        
}
public void printary(){
Journal5a call=newjournal5a();
int[]myArray=call.createArray(10);
除以十(myArray);
}
公共整数除以十(整数[]个){
整数计数=0;

for(i=0;整个数组中的iPass。然后循环调用它并调用if条件并返回最终计数。传递完整数组,而不是单个元素
System.out.println(“有”+call.divideByTen(myArray[i])+“可被10整除的数字”);
i
超出范围。此外,您可以在打印数字的循环中,添加
total+=call.divideByTen(myArray[i]);
然后打印
total
,不过需要一个新变量。