Erson Cokaj
Erson Cokaj

Reputation: 46

Two dimensional array in Java

I'm trying to make a two dimensional array and output the results [3][3] in 3 lines and 3 colons, but I get it like 123456789 in a straight line. Now I know that I get this result because of the "println" command but I would like to know how can I get it work the way I want it to. Sorry, I'm new to programming.

   import java.util.Scanner;
    public class klasa {
        public static Scanner lexo = new Scanner(System.in);
        public static void main(String[]args){

            int[][] array = new int[3][3];
            for(int a=0;a<3;a++){
                for(int b=0;b<3;b++){
                    System.out.println("Shkruaj numrat: ");
                    array[a][b]= lexo.nextInt();
                    }
                }
            for(int a =0; a<3;a++){
                for(int b=0;b<3;b++){
                    System.out.println(array[a][b]);

                }

            }


        }
    }

Upvotes: 0

Views: 94

Answers (3)

Alan Stokes
Alan Stokes

Reputation: 18964

       for(int a = 0; a<3; a++){
            for(int b=0; b<3; b++){
                System.out.print(array[a][b]);
                System.out.print(" ");
            }
            System.out.println();
        }

(That prints trailing spaces on each line, but it's a decent start.)

Upvotes: 1

Jason C
Jason C

Reputation: 40315

Use plain old print for each value, then print a newline after each row in your outer loop.

In general make your code reflect precisely what you are trying to do: Print each element in a row, followed by a newline. The computer generally follows your instructions to the letter.

Upvotes: 0

lacraig2
lacraig2

Reputation: 655

You should try:

for(int a = 0; a < 3;a++){
    for(int b = 0; b < 3;b++){
        System.out.print(array[a][b] + " ");
    }
    System.out.println();    //new line
}

to make a new line only after three elements (and add spaces (optional)).

Hope this helps.

Upvotes: 1

Related Questions