简体   繁体   中英

how to get user input in 2D char array-java

i am trying to take input from the using in a 2d char array where the output should be like :

110

1_0

11_

_11

0__

this can have as many combinations as 2^n where n is also user input. how can i create this output?

public static void main (String args[])

{ Scanner sc = new Scanner(System.in); 
  System.out.println("Enter Value i:  ");
      int i = sc.nextInt();
  int j =(int) Math.pow(2,i);
  char[][]array = new char[i][j];
      for (int k=0;k<i;k++)
    for (int s=0;s<j;s++)
    { array[k][s]= ?;  //i am stuck here

        }
Scanner scan=new Scanner(System.in);

char inputArray[][] = new char[rows][cols];

for (int i = 0; i < rows; i++)
{ 
    for (int j = 0; j < cols; j++)
    { 
        inputArray[i][j] = scan.next().charAt(0);
    } 
} 
Scanner in = new Scanner(System.in);
int rows = scan.nextInt();
int cols = scan.nextInt();

char arr[][] = new char[rows][cols]; // 2D char array
        for (int i = 0; i < rows; i++) {
            String data = "";
            if (in.hasNext()) { // input from user 
                data = in.next();
            } else {
                break;
            }
            for (int j = 0; j < cols; j++)
                arr[i][j] = data.charAt(j); 
        }
// to get a 2D char array
System.out.println(Arrays.deepToString(arr));

The input will be of the form -

4 // no. of rows
5 // no. of columns
10100
10111
11111
10010

to get a 2D char array as-

[[1, 0, 1, 0, 0], [1, 0, 1, 1, 1], [1, 1, 1, 1, 1], [1, 0, 0, 1, 0]]

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