我正在尝试查找用户在java中输入的2D数组中的奇数总数。我还试图找到所有这些奇数的总和。我想出了如何在严格平方的2d数组(即2x2、3x3、4x4等)中找到奇数个数,但是当我输入例如2x3或说5x6的数组大小时,输出不正确。我在做什么错了?
import java.util.Scanner;
public class SumOfOdd
{
public static void main (String []args)
{
Scanner input = new Scanner (System.in);
System.out.println("No. of rows");
int rows = input.nextInt();
System.out.println("No. of columns");
int cols = input.nextInt();
int [][] array1 = new int[rows][cols];
System.out.println("Input array elements");
for(int row = 0; row < rows; row++)
{
for(int col = 0; col < cols; col++)
{
array1[row][col] = input.nextInt();
}
}
int count = 0;
for(int i = 0; i < array1.length; i++)
{
for(int j = 0; j < array1.length; j++)
{
if(array1[i][j] % 2 == 1)
{
count++;
}
}
}
System.out.println("Odd number count = " + count);
}
}
答案 0 :(得分:2)
替换
for(int j = 0; j < array1.length; j++)
使用
for(int j = 0; j < array1[i].length; j++)
答案 1 :(得分:1)
最后替换嵌套的for循环
("0" + number).slice(-2)
与
for(int i = 0; i < array1.length; i++)
{
for(int j = 0; j < array1.length; j++){