Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Lets find and fix the BUG... I need you help...

the program sums the major diagonal of some n dimension matrix. I noticed that even if I put dimension as 4, and then insert the values of row 0 i can put 30 n number eventhough the program will not use them. can I add an If() somehow to limit the number, when asked for the values of row 0, for example?

import java.util.Scanner;

public class SumMajorDiagonal {

public static double sumMajorDiagonal(double[][] m){
    int n = m.length;
    int i=0;
    int j=0;

    double sum = 0;

    while(i < n && j < n){
        sum += m[i][j];
        i++;
        j++;
    }

    return sum;
}

public static void main(String args[]){

    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter dimension n of nxn matrix:");
    int n = Integer.parseInt(scanner.nextLine());

    double[][] mat = new double[n][n];

    for(int i=0; i<n; i++){
        System.out.print("Enter row " + i + ":");
        String[] row = scanner.nextLine().split(" ");

        for(int j=0; j<n; j++){
            mat[i][j] = Double.parseDouble(row[j]);
        }
    }


    System.out.print(sumMajorDiagonal(mat));

}

}

1 Answer

Thank you for your time