简体   繁体   中英

Printing the even numbers in the columns of 2D array

hello guys I am struggling to find the right way to print only the even numbers of the array.

I made a 1 dimensionnal array to save the element of the columns and then make sure if the index of the col%2==0 put that number in the output.

import java.util.Scanner;
public class Matrix {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        //array with 3 row in 5 col
        int[][] matrix = new int[3][5];
        //int []y = new int[5];
        // to impalement th array
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 5; j++) {
                System.out.print("Enter matrix[" + i + "][" + j + "]: ");
                matrix[i][j] = input.nextInt();
            }
            System.out.print("\n");
        }
        System.out.print("matrix values \n");
        // to show up  the originally array
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 5; j++) {
                System.out.print(matrix[i][j] + "\t");
            }
            System.out.print("\n");
        }
        //////the new array to display only the even numbers in the col
        System.out.print("\n");
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 5; j++) {
                int[] y = matrix[j];
                for (int k = 0; i < y.length; i++) {
                    if (y[k] % 2 == 0)
                        System.out.println(y[k]);
                }
            }
        }
    }
}

the output doesn't print the new array

    matrix values 
1   2   3   4   5   
6   7   8   9   10  
3   2   4   5   9   
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
    at Matrix.main(Matrix.java:43)

Replace i by k here:

for (int j = 0; j < 5; j++) {
    int[] y = matrix[j];
    for (int k = 0; i < y.length; i++) {
        if (y[k] % 2 == 0)
            System.out.println(y[k]);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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