0

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

                }

            }


        }
    }
3
  • Can you show what you want the output to look like? Commented Mar 10, 2015 at 0:01
  • 123 //new line 456 //new line 789 @AlanStokes Commented Mar 10, 2015 at 0:06
  • Then the answers you have will do it - just get rid of the spaces. Commented Mar 10, 2015 at 7:37

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.