数组中可被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();
}
# 1 楼答案
将数组传递给该方法,并使用该数组确定计数。你的算法看起来很合理。比如
或在Java 8+中,使用
IntStream
和filter
之类的然后你可以这样称呼它
或带有
printf
和类似内联的# 2 楼答案
你可以这样做。通过完整数组,然后检查除法是否为10。为了简单起见,跳过了其他部分