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?
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?