Hello! On top of the other program I have is one that deals with taking values from a file, "input.txt" (click on the file name), storing those values into a 2D array, and printing them out like so:
6 5 4 1
2 3 4 5
8 10 12 23
43 84 11 4
I also need to calculate the sum of the diagonal from the top left of the array to the bottom right of the array. In this case, the sum would be 25 (6+3+12+4).
And in addition to that, I need to make a transpose of that output and again calculate the sum of the diagonal from the top left of the array to the bottom right of the array like this:
6 2 8 43
5 3 10 84
4 4 12 11
1 5 23 4
Sum = 25
This is my code so far:
import java.io.*; import java.util.*; class Doubles { public static void main (String []args) { try { int i, j, n = 4; int[][] array = new int[n][n]; String line; FileInputStream fstream = new FileInputStream("input.txt"); Scanner scan = new Scanner(fstream); DataInputStream In = new DataInputStream(fstream); BufferedReader reader = new BufferedReader(new InputStreamReader(In)); //Stores data into an array while ((line = reader.readLine()) != null) { array[0][0] = line; } reader.close(); System.out.println("Here is the matrix version: "); for (i=0; i<n; i++) { for (j = 0; j<n; j++) { System.out.print(array[i][j]); } } } catch (Throwable e) { System.out.println("This is not valid!"); } } }
Obviously the code isn't done yet, but as you can tell I have no idea how to store the values into the 2D array, let alone calculate the sum and print that out. Any advice? Thanks in advance!