Learning coding, why the answer in the terminal shows up as a line rather than a matrix

Advertisements
public class BandMatrix {
    public static void main(String[] args) {
        int n = Integer.parseInt(args[0]);
        int w = Integer.parseInt(args[1]);
        for (int a = 1; a < n; a++) {
            for (int b = 1; b < n; b++) {
                if (Math.abs(a - b) > w) {
                    System.out.print("*  ");
                }
                else {
                    System.out.print("0  ");
                }
            }
        }
        System.out.println();
    }
}

This is what I have. When using the java BandMatrix 8 0 I get:

0  *  *  *  *  *  *  *  0  *  *  *  *  *  *  *  0  *  *  *  *  *  *  *  0  *  *  *  *  *  *  *  0  *  *  *  *  *  *  *  0  *  *  *  *  *  *  *  0

instead of it being a proper matrix.

Any changes I tried making just made the line either vertical or horizontal.

>Solution :

move

System.out.println();

one line up.

You need to do this inside the first ‘for’ loop, otherwise it will only print next line when both ‘for’ loops end.

Leave a ReplyCancel reply