简体   繁体   中英

Fill a 2d array with text file, comma separated values

Hi i want to fill a 2d array with comma separated values like this

3
1,2,3
4,5,6
7,8,0

first number the size of the array, the next values are the values of the array this is my code at the moment

   //readfile
   public static void leeArchivo()
{
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    try
    {
        //read first value which is teh size of the array
        size = Integer.parseInt(br.readLine());
        System.out.println("size grid" + size);
        int[][] tablero = new int[size][size];


        //fill the array with the values
        for (int i = 0; i < tablero.length; i++)
        {
            for (int j = 0; j < tablero[i].length; j++ )
            {
                tablero[i][j] = Integer.parseInt(br.readLine());
            }
        }
        br.close();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
}

This method is working fine for me, just another question, this will work if I want to insert another 2d array of the same size next to the other?

public static void leeArchivo()
{
    Scanner s = new Scanner(System.in);
    size = Integer.parseInt(s.nextLine());
    tablero = new int[size][size];
    boolean exit = false;
    while (!exit) {
        for (int i = 0; i < size; i++) {
            //quit commas to fill array
            String valuesStrArr[] = s.nextLine().split(",");
            for (int j = 0; j < size; j++) {
                tablero[i][j] = Integer.parseInt(valuesStrArr[j]);
            }
            if (i == size - 1)
                exit = true;
        }
    }
}

Example:

3
1,2,3
4,5,6
7,8,0
1,2,3
8,0,4
7,6,5
Scanner in = new Scanner(System.in);
int num = in.nextInt();

Use Scanner. Replace System.in with File.

First, you have to separate the elements.

You can do this using the String method split ( https://www.javatpoint.com/java-string-split )

//fill the array with the values
for (int i = 0; i < tablero.length; i++)
{
    String[] elements = br.readLine().split(",");
    for (int j = 0; j < tablero[i].length; j++ )
    {
        tablero[i][j] = Integer.parseInt(elements[j]);
    }
}
br.close();

Or you can use Scanner method, nextInt.

Regarding perfomance, the first option is better.

Solution using Scanner

Scanner s = new Scanner(System.in);
int size = Integer.parseInt(s.nextLine());
int[][] tablero = new int[size][size];
boolean exit = false;
while (!exit) {
    for (int i = 0; i < size; i++) {
        String valuesStrArr[] = s.nextLine().split(",");
        for (int j = 0; j < size; j++) {
            tablero[i][j] = Integer.parseInt(valuesStrArr[j]);
        }

        if (i == size - 1)
            exit = true;
    }
}

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