Home > Mobile >  How to print out the 2D Array in a certain order?
How to print out the 2D Array in a certain order?

Time:09-27

So I'm working on this file where we have to print out a 2D Array that has the odd numbers replaced with stars. But I can't seem to get the order right

public class TwoDimArray {
    public static int[][] myArray = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

    public static void main(String[] args) {
        printArray(myArray);
        System.out.println("______________________________");
        printArrayEven(myArray);
    }

    private static void printArray(int[][] theArray) {
        for (int i = 0; i < theArray.length; i  ) {
            for (int j = 0; j < theArray[i].length; j  )
                display(theArray[i][j]);
            System.out.println();
        }
    }

    private static void display(int num) {
        System.out.print(num   " ");
    }

    private static void printArrayEven(int[][] theArray) {
        for (int i = 0; i < theArray.length; i  ) {
            for (int j = 0; j < theArray[i].length; j  )
                if ((theArray[i][j]) % 2 == 0) {
                    display(theArray[i][j]);
                    System.out.println();

                } else {
                    System.out.println("*");
                }

        }
    }
} 

The first method prints out the order that I am looking for but the second one prints everything vertically.

enter image description here

How do I get the second method to print the same as the first method? Thanks.

CodePudding user response:

I think this should do it

    private static void printArrayEven(int[][] theArray) {
        for (int i = 0; i < theArray.length; i  ) {
            for (int j = 0; j < theArray[i].length; j  ) {
                if ((theArray[i][j]) % 2 == 0) {
                    display(theArray[i][j]);
                } else {
                    System.out.print("* ");
                }
            }
            System.out.println();
        }
    }

System.out.println() adds a newline at the end of the print statement so you need to use System.out.print() for the individual characters and print the new line after a row

  • Related