The program in its current state is supposed to read the text file second line onwards, store each individual line as an int array in a Row object and then add each Row object to a Row ArrayList inside a Matrix object.
Unfortunately when adding a new Row object the previously added instances of Row in the Matrix's ArrayList gets overridden to the same values of the newly added Row instance. I'm guessing this is some sort of reference issue here where all the Rows are pointing to the same address?
Row.java
public class Row {
int[] equation;
public Row(int[] equation) {
this.equation = equation;
}
public int[] getEquation() {
return equation;
}
@Override
public String toString() {
String s = "";
for (int i : equation) {
s += i + " ";
}
return s.trim();
}
}
Matrix.java:
public class Matrix {
List<Row> rows;
public Matrix () {
rows = new ArrayList<Row>();
}
public List<Row> getRows() {
return rows;
}
public void addNewRow(int[] equation) {
Row r = new Row(equation);
rows.add(r);
}
@Override
public String toString() {
String s = "";
for (Row r : rows) {
s += r + "\n";
}
return s.trim();
}
}
Main.java
public class Main {
public static void main(String[] args) {
File file = new File("in.txt");
int numOfEquations;
int[] equation;
Matrix m = new Matrix();
try (Scanner fileScanner = new Scanner(file)) {
numOfEquations = fileScanner.nextInt();
equation = new int[numOfEquations+1];
while (fileScanner.hasNextLine()) {
for (int i = 0; i < equation.length; i++) {
equation[i] = fileScanner.nextInt();
}
m.addNewRow(equation);
}
System.out.println(m);
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
}
}
}
in.txt
3
1 1 2 9
2 4 -3 1
3 6 -5 0
Expected output:
1 1 2 9
2 4 -3 1
3 6 -5 0
Actual output:
3 6 -5 0
3 6 -5 0
3 6 -5 0