Home > other >  What edits should I make to my code for it to print as expected
What edits should I make to my code for it to print as expected

Time:09-17

I'm trying to write a function myMethod that will print a pattern like this based on what the input k is:

In this case k = 7

#######
######
#####
####
###
##
#
##
###
####
#####
######
#######

However, I'm struggling to understand what modifications I'm supposed to do with my code in order for it to run.

Here is my code so far:

public class Diamond {
    static void myMethod(int k) {
        for (int j = -k; j <= k; j  ) {
            String m = "#";
            System.out.println((m.repeat(Math.abs(j))));
    }

    public static void main(Integer[]) {
        myMethod(9);
    }}

}

I am unable to run my code due to errors in placing ( and ;, however, even when I have added or remove tge ( and ;, the error still remains.

What am I doing wrong here?

CodePudding user response:

When jdk version is lower than JDK 11,we can use below code

    int k = 7;
    for (int j = -k; j <= k; j  ) {
        String m = "#";
        int abs = Math.abs(j);
        for (int i = 0; i < abs; i  ) {
            System.out.print(m);
        }
        if (abs > 0) {
            System.out.println();
        }
    }

Otherwise

    int k = 7;
    for (int j = -k; j <= k; j  ) {
        String m = "#";
        int abs = Math.abs(j);                
        System.out.println(m.repeat(abs));
    }
  • Related