1

I've been asked to read a file and take the text in there and convert them to a 2d array. Since Eclipse is a pain and wont open/read my text file, I made a test in the class that uses an individually initialized 2d array. My problem is that I don't know to put the parseInt'ed array back into the new one. Or how to use that to form a new 2d array. Here's my code: public static void main(String[] args) {

    String[][] tester = new String[][] { { "-1 2 3 0" }, { "-1 3 4 0" }, { "-1 3 -4 0" }, { "-1 -3 4 0" } };

    int row = 0;
    int col = 0;
    int count = 0;
    int[][] formula = new int[4][];

    while (count < 4) {
        String temp = tester[row][col];
        String[] charArray = temp.split("\\s+");
        int[] line = new int[charArray.length];

        for (int i = 0; i < charArray.length; i++) {
            String numAsStr = charArray[i];
            line[i] = Integer.parseInt(numAsStr);
            //what to do here??
        }

        row++;
        count++;

    }

    System.out.println(Arrays.deepToString(formula).replace("], ",
     "]\n"));
}
}

I want to generate an array that reads like this:

-1 2 3 0

-1 3 4 0

-1 3 -4 0

-1 -3 4 0

How can I accomplish this?

Philipp Jahoda
  • 50,880
  • 24
  • 180
  • 187
teddymv
  • 49
  • 1
  • 9

5 Answers5

1

You have to add items to the array formula. Just add formula[count] = line; here:

for (int i = 0; i < charArray.length; i++) {
        String numAsStr = charArray[i];
        line[i] = Integer.parseInt(numAsStr);
        formula[count] = line;
    }

and the output is:

[[-1, 2, 3, 0]
[-1, 3, 4, 0]
[-1, 3, -4, 0]
[-1, -3, 4, 0]]

Select as answer if it worked!

Alex Cuadrón
  • 638
  • 12
  • 19
1

Change the definition of formula like this:

int[][] formula = new int[tester.length][];

You want the formula to have the same number of rows as the tester, right?

Also change your while loop to loop until tester.length instead of a constant 4:

while (counter < tester.length)

Now, after the for loop is where the real business begins:

for (int i = 0; i < charArray.length; i++) {
    String numAsStr = charArray[i];
    line[i] = Integer.parseInt(numAsStr);
}
formula[row] = line; // <------------

During the for loop, you've parsed all the integers in one row of the tester. Now it is time to put the row of integers into formula, isn't it?

Sweeper
  • 213,210
  • 22
  • 193
  • 313
1

How to read a large text file line by line using Java? Java file to 2D array

-1 2 3 0
-1 3 4 0
-1 3 -4 0
-1 -3 4 0

Demo

import java.io.File;
import java.util.Arrays;
import java.util.Scanner;
import java.io.IOException;

public class MyFile {
    public static void main(String[] args) throws IOException {

        File file = new File("myFile.txt"); // read file name
        Scanner scan = null;

        int[][] myArray = new int[4][4]; // how many?
        String line = null; // line in .txt
        String[] token = null; // number token

        try {
            scan = new Scanner(file);
            while (scan.hasNextLine()) {
                for (int i = 0; i < 4; i++) { // loop thru row
                    line = scan.nextLine(); // scan line
                    token = line.split(" ");

                    for (int j = 0; j < 4; j++) {
                        myArray[i][j] = Integer.parseInt(token[j]);// loop thru col & parse token int
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        scan.close();
        System.out.println(Arrays.deepToString(myArray)); //fix this
    }
}
CaptainMar
  • 69
  • 7
1

I would advice you to use a List where you could store the arrays and then it's easily convertible into int[][]...

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        String test = "-1 2 3 0\n-1 3 4 0\n-1 3 -4 0\n-1 -3 4 0";

        Scanner sc = new Scanner(test);

        //read
        List<int[]> arrayList = new ArrayList<>();

        while (sc.hasNextLine()) {
            arrayList.add(Arrays.stream(sc.nextLine().split(" "))
                    .mapToInt(Integer::parseInt)
                    .toArray());
        }

        //print
        arrayList.forEach(arr -> {
            Arrays.stream(arr).forEach(item -> System.out.print(item + " "));
            System.out.println();
        });

        //convert
        int[][] matrix = new int[arrayList.size()][];
        matrix = arrayList.toArray(matrix);


        //print
        Arrays.stream(matrix).forEach(arr -> {
            Arrays.stream(arr).forEach(item -> System.out.print(item + " "));
            System.out.println();
        });

    }

}

Just beware of the fact that if you have to split it on more then one regex pattern you will have to use a flatmap for each of the lines.

dbl
  • 1,109
  • 9
  • 17
0

add formula[row] = line; under the for loop

parsa
  • 987
  • 2
  • 10
  • 23