简体   繁体   中英

How can I display my 2-d array with this code?

I am trying to make a 3x3 dimension(area of movements) using 2Dimensional array. My only problem is that as I run the program and chose left direction, the 3x3 dimension doesnt appear. It only shows 0. I wanna see the 3x3 dimension. What's the problem with my code?

Scanner input = new Scanner(System.in);

    int[][]arr = {{0,0,0},{0,0,0},{0,0,0}};

    int turtle =1;

    for(int i=0;i<3;i++){
        for(int j=0;j<3;j++){

            System.out.println ("(1)Left(2)Right(3)Up(4)Down");
            int movement = input.nextInt();

            if(movement == 1){
                if(turtle==1){
                    turtle = 1;
                    System.out.println ("Cant move left");
                }
                if(turtle ==2){
                    arr[0][0] = 1;
                    turtle = 3;
                }
                if(turtle ==3){
                    arr[0][2] = 1;
                    turtle = 2;

                }
                if(turtle ==4){
                    System.out.println ("Cant move left");
                    turtle = 4;
                }
                if(turtle ==5){
                    arr[1][0] = 1;
                    turtle = 4;
                }
                if(turtle ==6){
                    arr[1][1] = 1;
                    turtle = 5;
                }
                if(turtle ==7){
                    System.out.println ("cant move left");
                    turtle = 7;
                }
                if(turtle ==8){
                    arr[2][0] = 1;
                    turtle = 7;
                }
                if(turtle ==9){
                    arr[2][1] = 1;
                    turtle = 8;
                }
            }

            System.out.printf ("%d",arr[i][j]);
        }
        System.out.println ();
    }

Try this.

import java.util.Arrays;

for (int[] a : arr) {
  System.out.println(Arrays.toString(a);
}

The other way would be to do the following.


for(int [] a : arr) {
   for (int i = 0; i < a.length; i++) {
      System.out.print(a[i] + " " );
   }
   System.out.println();
}

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