[英]create 2d array then using user input print the total number of odd no. and the sum of the odd numbers in that array
This what I have done so far. 到目前为止,这是我所做的。 I can't get to print the total number of odd numbers in the array and the sum of that odd numbers.
我无法打印数组中奇数的总数以及这些奇数的总和。
import java.util.Scanner;
public class arrayssumofodd
{
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
int rows=scan.nextInt();
int columns=scan.nextInt();
int array[][]=new int [rows][columns];
int odd=0;
int sum=0;
int num=0;
for(int i=0;i<rows;i++)
{
for(int j=0; j<columns;j++)
{
array[i][j]=scan.nextInt();
num=array[i][j];
}
for(int k=0;k<rows;k++)
{
for(int m=0;m<k;m++)
{
if(num%2!=0)
{
odd++;
sum+=odd;
}
}
}
}
System.out.println("Odd number count "+" = " +odd);
System.out.println("Sum of odd numbers "+" = " +sum);
}
}
I've tried everything to get the odd numbers to print but I haven't been able to. 我已经尝试了所有方法以打印出奇数,但我一直无法做到。 It keeps outputting zero when I run the program.
当我运行程序时,它始终输出零。
Your for loops are mixed with each other. 您的for循环相互混合。
for(int i=0;i<rows;i++)
{
for(int j=0; j<columns;j++)
{
array[i][j]=scan.nextInt();
num=array[i][j];
// you can do operation with odd count and sum here
}
Or you can use the same two for loops to go through the numbers in the 2D array and just count the odd number and find the sum. 或者,您可以使用相同的两个for循环遍历2D数组中的数字,然后仅对奇数进行计数并求和。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.