O
O
Otakukz172021-07-16 21:36:15
Java
Otakukz17, 2021-07-16 21:36:15

How to solve a two-dimensional Java array problem?

I am currently learning Java SE. And I came across this problem:
Write a program in which I enter two numbers N and M. Then I create a two-dimensional array NxM. Next, we fill this array with numbers. Then, we enter the number k. The program should output the first k negative entries in each column, as shown in the example.
Input:
3 3
9 -2 0
-8 -7 -2
1 12 -3
2
Output:
9 -2 0
-8 -7 -2
1 12 -3
_ _ _
-8 -2 -2
X -7 -3

I wrote the following code which outputs the first k negative elements, but I can't seem to get the output from the example
My code:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int N = in.nextInt();
        int M = in.nextInt();
        int[][] a = new int[N][M];
        for (int i = 0; i < N; i++) {
            for (int x = 0; x < M; x++) {
                a[i][x] = in.nextInt();
            }
        }
        int k = in.nextInt();
        for (int i = 0; i < N; i++, System.out.println()) {
            for (int x = 0; x < M; x++) {
                System.out.print(a[i][x] + " ");
            }
        }
        System.out.println("_____");
        for (int i = 0; i < N; i++, System.out.println()) {
            for (int x = 0; x < M; x++) {
                if (a[i][x] < 0) {
                    if (i <= k) {
                        System.out.print(a[i][x] + " ");
                    }
                }
            }
        }
    }
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question