简体   繁体   中英

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]);

                }

            }


        }
    }

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.

       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.)

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.

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