简体   繁体   中英

Nested for-loops

I've gotten my code to behave as expected except for one last bit.

I'm having problems with my last for-loop. I just need it to start on the right side (or right- justified) instead of how it is now - it's starting on the left side (it's left-justified).

Here's the output on my terminal (it's the last set (the 4th set) of asterisks I'm having an issue with).

在此处输入图像描述

Here's my code.

public class Triangles
{
  // draw four triangles
  public static void main(String[] args) 
  {
    int row;               // the row position
    int column;            // the column position
    int space;             // number of spaces to print
    int numLines = 10;     // the number of lines per triangle

    
    for (row = 1; row <= numLines; row++)
    {
       for (column = 1; column <= row; column++)
         System.out.print("*");
       System.out.println();
    } // end first for-loop
    System.out.println();

   

    for (row = 1; row <= numLines; row++)
    {
        for (column = 10; column >= row; column--)
          System.out.print("*");
        System.out.println();
    } // end second for-loop
    System.out.println();

    
      for (row = numLines; row >= 1; row--)
      {
         for (space = numLines; space > row; space--)
           System.out.print(" ");
         for (column = 1; column <= row; column++)
           System.out.print("*");
         System.out.println();
       } // end third for loop
       System.out.println();
      
       // !! This is the for-loop I'm having an issue with!!
       for (row = numLines; row >=1; row--) {
         for (space = numLines; space < numLines; space--)
           System.out.print(" ");
         for (column = numLines; column >= row; column--) 
           System.out.print("*");
         System.out.println();
       } // end fourth for loop
   } // end main
} // end class Triangle

Thanks in advance for all your help: )

3rd shape and 4th shape are almost same. Just start the 1st loop in 3rd shape from opposite direction in 4th shape and leave the other thing as it is.

    int row;               // the row position
    int column;            // the column position
    int space;             // number of spaces to print
    int numLines = 10;     // the number of lines per triangle

      
      // !! This is the for-loop I'm having an issue with!!
      for (row = 1; row <=numLines ; row++) {
         for (space = numLines; space > row; space--)
           System.out.print(" ");
         for (column = 1; column <= row; column++)
           System.out.print("*");
         System.out.println();
       } // end third for loop
       System.out.println(); // end fourth for loop

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