簡體   English   中英

如何在輸入的二維數組java中找到奇數的數量和所有奇數的總和?

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

我試圖在用戶在 java 中輸入的二維數組中找到奇數的總數。 我也在試圖找到所有這些奇數的總和。 我已經想出了如何在嚴格的方形二維數組(即 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);
    }
}

代替

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

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

最后替換嵌套的for循環

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

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