有 Java 编程相关的问题?

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

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

我被分配了一个任务,让我创建了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) 个答案

  1. # 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());
    
  2. # 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;        
    }