[英]create 2d array then using user input print the total number of odd no. and the sum of the odd numbers in that array
到目前為止,這是我所做的。 我無法打印數組中奇數的總數以及這些奇數的總和。
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);
}
}
我已經嘗試了所有方法以打印出奇數,但我一直無法做到。 當我運行程序時,它始終輸出零。
您的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
}
或者,您可以使用相同的兩個for循環遍歷2D數組中的數字,然后僅對奇數進行計數並求和。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.