简体   繁体   English

如何在输入的二维数组java中找到奇数的数量和所有奇数的总和?

[英]How to find the amount of odd numbers and thee sum of all odd numbers in a inputted 2D array java?

I'm trying to find the total amount of odd numbers in a 2D array inputted by the user in java.我试图在用户在 java 中输入的二维数组中找到奇数的总数。 I'm also trying to find the sum of all those odd numbers.我也在试图找到所有这些奇数的总和。 I've figured out how to find the number of odd numbers in a strictly square 2d array (ie. 2x2, 3x3, 4x4, etc) but when I input an array size of for example 2x3 or say 5x6 the output is incorrect.我已经想出了如何在严格的方形二维数组(即 2x2、3x3、4x4 等)中找到奇数的数量,但是当我输入数组大小(例如 2x3 或 5x6)时,输出是不正确的。 What am I doing wrong?我究竟做错了什么?

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);
    }
}

Replace代替

for(int j = 0; j < array1.length; j++)

with

for(int j = 0; j < array1[i].length; j++)

Replace the nested for loop in the end最后替换嵌套的for循环

for(int i = 0; i < array1.length; i++) { for(int j = 0; j < array1.length; j++){

with

for(int i=0;i<rows;i++) { for(int j=0;j<cols;j++) {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM