The program below asks the user for the size of the multidimensional array and creates it. Then, I want to add the total of each rows and display it. I'm having trouble with that. My program adds the total from the previous row and add it to the current total. How can I fix this?
This is what it should look like
How big would you like your matrix? Rows - ? 2 Cols - ? 2 Please enter your row 1? Column 1 - 1 Column 2 - 2 Please enter your row 2? Column 1 - 3 Column 2 - 4 Your total for row 1 is - 3 Your total for row 2 is - 7 Your total for the 2 x 2 matrix is 10
This is what it looks like now
How big would you like your matrix? Rows - ? 2 Cols - ? 2 Please enter your row 1? Column 1 - 1 Column 2 - 2 Please enter your row 2? Column 1 - 3 Column 2 - 4 Your total for row 1 is - 3 Your total for row 2 is - 10 Your total for the 2 x 2 matrix is 13
import java.util.Scanner; public class ArraySum { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int rows, cols, colValue, rowTotal, matrixTotal; rowTotal = 0; matrixTotal = 0; System.out.println("How big would you like your matrix?"); System.out.print("\tRows - ? "); rows = scan.nextInt(); System.out.print("\tCols - ? "); cols = scan.nextInt(); System.out.println(); int[][] numberArray = new int[rows][cols]; for(int a=0; a<numberArray.length; a++) { System.out.println("Please enter your row " + (a+1) + "?"); for(int b=0; b<numberArray[0].length; b++) { System.out.print("\tColumn " + (b+1) + " - "); colValue = scan.nextInt(); numberArray[a][b] = colValue; } System.out.println(); } for(int c=0; c<numberArray.length; c++) { for(int d=0; d<numberArray[0].length; d++) { rowTotal = rowTotal + numberArray[c][d]; } matrixTotal = matrixTotal + rowTotal; System.out.println("Your total for row " + (c+1) + " is - " + rowTotal); } System.out.println(); System.out.println("Your total for the " + rows + " x " + cols + " matrix is " + matrixTotal); } }