计数在数组中可以被10整除的数字
问题描述:
我被赋予了一个赋值,它使我创建了3个方法来创建一个数组,打印一个数组并计算数组中所有可被10整除的数字。这是给我的最麻烦的部分是计算由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 divideByTen(int[] nums) {
int count = 0;
for (int num : nums) {
if (num % 10 == 0) {
count++;
}
}
return count;
}
或,在Java 8+,使用IntStream
和filter
像
return (int) IntStream.of(nums).filter(x -> x % 10 == 0).count();
然后你可以用printf
调用它
System.out.println("There are " + call.divideByTen(myArray)
+ " numbers that are divisible by 10");
或并内联像
System.out.printf("There are %d numbers that are divisible by 10.%n",
IntStream.of(nums).filter(x -> x % 10 == 0).count());
+0
另外,你可以在打印数字的循环中添加total + = call.divideByTen(myArray [i]);'然后打印total,尽管需要一个新的变量。 –
答
你可以这样做。通过完整的数组,然后检查除以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;
}
传入整个数组中。然后通过它循环并调用你的if条件并返回最终计数。 –
传递完整数组,而不是单个元素 – Hemal
'System.out.println(“存在”+ call.divideByTen(myArray [i])+“可被10整除的数字”);''i'超出了范围。 –