简体   繁体   中英

how do I get my diagonal line to start printing from the bottom left of my asterik box?

I am making a code that is to practice for creating methods and calling them in the main method. I am having trouble with an output that is not exactly how it is supposed to look like. The code is supposed to create a box based on the input 9. This is the output of my code:

*********
*+      *
* +     *
*  +    *
*   +   *
*    +  *
*     + *
*      +*
*********

I can't figure out how to get the "+" diagonal to start from the bottom left of the box to the top right. my code is this:

 public static void main(String[] args)
   {
   System.out.print(boxWithMinorDiagonal(9));
   }
   
   public static int boxWithMinorDiagonal(int n){
      for (int col = 1; col <= n; col++) {
         for (int row = 1; row <= n; row++) {
             if(row == 1 || col == 1 || row == n || col == n){
               System.out.print("*");
              }
             else if (col == row){
             System.out.print("+");
             }
            else{
            System.out.print(" ");
            }
       
         

      }
       System.out.println();
      }
      return n;
      } 

I think I need to get the row and col to start from the bottom left, which would start the diagonal from there, but am not exactly sure what I would need to change in my for loops to get the row and col to start from the bottom left.

Right now you draw a star if eg the col is 1 and the row is 1, or the col is 2 and the row is 2.

Make a table of which row/col combos should produce a star for bottom-left to top-right, then try to find a pattern in this you can put in terms of a mathematical operation that returns a boolean.

HINT: col + row == something might be something you want to check out.

just change this part : else if (col == n-row+1){ System.out.print("+");}
So your code will be :

    {
        System.out.print(boxWithMinorDiagonal(9));
    }

    public static int boxWithMinorDiagonal(int n){
        for (int col = 1; col <= n; col++) {
            for (int row = 1; row <= n; row++) {
                if(row == 1 || col == 1 || row == n || col == n){
                    System.out.print("*");
                }
                else if (col == n-row+1){
                    System.out.print("+");
                }
                else{
                    System.out.print(" ");
                }



            }
            System.out.println();
        }
        return n;

and you'll get this:

*********
*      +*
*     + *
*    +  *
*   +   *
*  +    *
* +     *
*+      *
*********
9

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM