Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
173 views
in Technique[技术] by (71.8m points)

How to create a Java 2D array with 1s and 0s?

The printed result should be like this (I don't know how to format it, but imagine a 9x9 2d array where the 1's create an X):

1 0 0 0 0 0 0 0 1
0 1 0 0 0 0 0 1 0
0 0 1 0 0 0 1 0 0
0 0 0 1 0 1 0 0 0
0 0 0 0 1 0 0 0 0
0 0 0 1 0 1 0 0 0
0 0 1 0 0 0 1 0 0
0 1 0 0 0 0 0 1 0
1 0 0 0 0 0 0 0 1

This is what I have so far:

int [][] myArray = new int[9][1]; 
    
for (int row = 0 ; row < 9 ; row++)
    for (int column = 0 ; column < 1 ; column++)
        myArray[row][column]= 0; 

How would I create a while loop for this?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try the following code:

public class Main
{
static int SIZE = 9;

 public static void main(String []args){
    int[][] arr = new int[SIZE][SIZE];
    for(int i = 0; i < SIZE; i++){
        arr[i][i] = 1;
        arr[i][SIZE-1-i] = 1;
    }
    printArr(arr);
 }
 
 public static void printArr(int[][] arr){
     for(int i = 0; i < SIZE; i++)
       {
          for(int j = 0; j < SIZE; j++)
          {
             System.out.print(arr[i][j] + " ");
          }
          System.out.println();
       }
    }

}

I have added a print method so you will see the desired result. few points about the above code:

  1. there is no need to set all values to 0. this is by default.
  2. so the only thing that left to do is to set the diagonals to 1's. that can be done in 1 for loop as suggested above. the first line in the loop creates the diagonal from top left to bottom right. the second line creates the other diagonal
  3. you can change SIZE variable to any size that you want, I set it to 9, but it can be any int.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.6k users

...