2

I have to get input of 6x6 in 2-D array. In this code the input is taken String and not directly into interger ? And why the split function is used ? I didn't understand the code after the first for loop ?

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {

    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        int[][] arr = new int[6][6];

        for (int i = 0; i < 6; i++) {
            String[] arrRowItems = scanner.nextLine().split(" ");
            scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

            for (int j = 0; j < 6; j++) {
                int arrItem = Integer.parseInt(arrRowItems[j]);
                arr[i][j] = arrItem;
            }
        }
        scanner.close();
    }
}
Arun Sudhakaran
  • 2,167
  • 4
  • 27
  • 52
Mercury1337
  • 333
  • 4
  • 13
  • 1
    Because: 1) you're reading a *line* at a time, and 2) the "line" may contain *multiple* numbers. 3) The "split()" allows you to "separate" the numbers from each other, so you can "parseInt()" individually. Q: Make sense? – paulsm4 Feb 23 '19 at 05:36

3 Answers3

0

By default in almost programming languages like JAVA, and Python the input is taken in form of String. Also C has int main(int argc, char[] argv) which represents a string. Thus, you need to parse it and convert it to integer values.

0

Given the solution, the input must be of the form (space separated)

1 2 3 4 5 6

7 8 9 10 11 12

13 14 15 16 17 18

19 20 21 22 23 24

25 26 27 28 29 30

31 32 33 34 35 36

Now, you would want to iterate for each row of the input. Hence the outer i loop. Once you read the line as a string after skipping the junk characters, you need to separate the numbers. This is done using split with space as delimiter. This split gives you the 6 numbers as an array of strings. For each of these strings, convert them to int using parseInt. Do this for all the rows and you're done.

Aditya Pal
  • 103
  • 1
  • 1
  • 8
0
  1. Yes, the input is taken directly as a String.

  2. Your code assumes you will insert 6 rows of 6 numbers. An example of the first row inserted could be:

    2 4 6 7 8 9

This method splits this string around matches of the given regular expression.

  1. The code before the first loop means:

private static final Scanner scanner = new Scanner(System.in);

A simple text scanner which can parse primitive types and strings using regular expressions.

int[][] arr = new int[6][6];

New multidimensional integer array declared and instanced with 6 elements that contains 6 elements each one. See more.

If you don't understand the basic structure of the java program, i recommends you start from here.

Thank you.

Capriatto
  • 947
  • 1
  • 8
  • 17