Advertisement
mmayoub

Loops - execise no 05 slide no 67

Jun 27th, 2017
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.32 KB | None | 0 0
  1. package class170629;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class LoopsEx05Slide67 {
  6.  
  7.     public static void main(String[] args) {
  8.         // input: integer number.
  9.         // output: triangle of asterisks
  10.  
  11.         // create a scanner
  12.         Scanner s = new Scanner(System.in);
  13.  
  14.         // ask for input
  15.         System.out.print("Enter an integer number: ");
  16.         // get and save input value
  17.         int n = s.nextInt();
  18.  
  19.         // close scanner
  20.         s.close();
  21.  
  22.         // for each row
  23.         for (int row = 1; row <= n; row += 1) {
  24.             // print asterisks on the left
  25.             for (int ast = 0; ast < row; ast += 1) {
  26.                 System.out.print("*");
  27.             }
  28.             // print spaces first
  29.             for (int spc = 0; spc < 2 * (n - row); spc += 1) {
  30.                 System.out.print(" ");
  31.             }
  32.             // print asterisks on the right
  33.             for (int ast = 0; ast < row; ast += 1) {
  34.                 System.out.print("*");
  35.             }
  36.  
  37.             // end of the line
  38.             System.out.println();
  39.         }
  40.  
  41.         System.out.println();
  42.         /*
  43.          * second solution: using String format and printf
  44.          */
  45.         // for each row
  46.         for (int row = 1; row <= n; row += 1) {
  47.             // build string of asterisks
  48.             String ast = String.format("%" + row + "s", " ").replace(" ", "*");
  49.             // build string of spaces
  50.             String spc = row == n ? "" : String.format("%" + 2 * (n - row)
  51.                     + "s", " ");
  52.  
  53.             // print the row
  54.             System.out.printf("%s%s%s\n", ast, spc, ast);
  55.         }
  56.  
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement