Home > front end >  console program
console program

Time:11-23

amking a tile console generator

My code so far is:

// if true
        if(pattern == true) {
        for(int i=0;i<length;i  ) {
            for(int j=0;j<height;j  ) {
                if(j%3 == 0) {
                    output[i][j]  = main;
                }
                else {
                    if(i%3 == 0) {
                        output[i][j] =main;
                    }
                    else {
                        output[i][j]  = filler;
                    }
                }
            }
            output[i][j] = "\n";
        }
        }

I tried using a temp variable to increment but had no luck with the issue stated above

CodePudding user response:

public static void crosses(int height, int length, char main, char filler, boolean pattern) {
    char[][] output = new char[height][length];
    if(pattern == false) {
        for(int i = 0; i<length; i  ) {
            for (int j = 0; j < height; j  ) {
                if (j == (i - 2) || j == (i   2) || j == (height - i - 3) || j == (height - i   1)) {
                    output[i][j] = main;
                }
                else {
                    output[i][j] = filler;
                }
            }
        }
    }
    for (char[] row : output) {
        for (char c : row) {
            System.out.print(c);
        }
        System.out.println();
    }
}

The above works as close to your code as possible, but here are a few improvements to the way you wrote it:

public static char[][] crosses(int height, int length, char main, char filler, boolean pattern) {
    char[][] output = new char[height][length];
    if (pattern) {
        for (char[] row : output) { Arrays.fill(row, filler); }
        return output; // I made an assumption that if true, the output should be filled with filler only.
    }
    // no need to do pattern == false, just leave using return if true.
    for(int i = 0; i<length; i  ) {
        for (int j = 0; j < height; j  ) {
            if (j == (i - 2) || j == (i   2) || j == (height - i - 3) || j == (height - i   1)) {
                output[i][j] = main;
            }
            else {
                output[i][j] = filler;
            }
        }
    }
    return output; // Better to delegate the print to the caller, so they can decide how to print it.
}

public static void main(String[] args) {
    char[][] result = crosses(12, 12, 'x', '.', false);
    for (char[] row : result) {
        System.out.println(row); // better than another for loop as it's already built in.
    }
}
  • Related