Home > Software design >  Reading a string splitting it and assigning values to 2D array in JAVA
Reading a string splitting it and assigning values to 2D array in JAVA

Time:11-07

I am trying to split a string with " "(space) and assigning each value on row to each respective array.

The input file contains:

4
2 2
1 3
4 7
3 4

The first line of the file has a single integer value N which is number of jobs.

The next N lines will represent a job, each with 2 values.

How do I start reading from second line from a Input file?

I want to split from Second line and assign it to 2D array. So if (2,2) is there on second line, then 2 should be assigned to array[0][0] and the other 2 to array[0][1]. For next line 1 should be assigned to array[1][0] and 3 should be assigned to array[1][1].

int num = scan.nextInt();  // taking number of jobs from first line
int[][] array = new int[num][num];
       
while (scan.hasNext())      //It reads till file has next line
{
    String str = scan.nextLine(); 
    for (int i = 0; i < num; i  ) {
        for (int j = 0; j < num; j  ) {
            array[i][j] = scan.nextInt();
        }
    }
}

Had done till here, couldn't figure out further.

CodePudding user response:

int[][] array = new int[num][num];

Wrong dimensions of the array, for N = 4 you create array of 4 * 4, not 4 * 2.

Since the number of columns is fixed in your case, you should create array as new int[num][2] and update reading of the data accordingly.

String str = scan.nextLine();
for (int i = 0; i < num; i  ) {
   for (int j = 0; j < num; j  ) {
       array[i][j] = scan.nextInt();
   }
}

Reading a line just to skip it may be redundant if you use Scanner to read the integer numbers using nextInt. So actually you do NOT need to read the data line by line, then split each line into String parts, and convert each part into a number because Scanner class takes care of it.

Also, the innermost loop tries to read N numbers per array row, while it's better to refer actual length of the array in the row.

Thus, it should be ok just to read the data according to the task using Scanner only:

int num = scan.nextInt();  // taking number of jobs from the first line

// preparing array of N rows and 2 columns
int[][] array = new int[num][2];
       
for (int i = 0; i < num; i  ) {
    for (int j = 0; j < array[i].length; j  ) { // reading 2 ints per row
        array[i][j] = scan.nextInt();
    }
}

CodePudding user response:

You can make it a lot easier by just ignoring the first line and letting Java do the hard work:

import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;
import java.util.Arrays;

public class FileToArray {
    public static void main(String[] args) {
        try {
            try (Stream<String> stream = Files.lines(Path.of("arr.txt"))) {
                String[][] nums = stream.skip(1).map(s -> s.split(" ")).toArray(String[][]::new);
                System.out.println(Arrays.deepToString(nums));
            }

        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
}
  • Related