Advertisement
mmayoub

Loops - execise no 04 slide no 66

Jun 27th, 2017
189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.24 KB | None | 0 0
  1. package class170629;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class LoopsEx04Slide66 {
  6.  
  7.     public static void main(String[] args) {
  8.         // input: integer number.
  9.         // output: triangle aligned to right
  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.         /*
  23.          * first solution: printing single char every time
  24.          */
  25.         // for each row
  26.         for (int row = 0; row < n; row += 1) {
  27.             // print spaces first
  28.             for (int spc = 0; spc < row; spc += 1) {
  29.                 System.out.print(" ");
  30.             }
  31.  
  32.             // print asterisks
  33.             for (int ast = 0; ast < n - row; ast += 1) {
  34.                 System.out.print("*");
  35.             }
  36.  
  37.             // end of the line
  38.             System.out.println();
  39.         }
  40.  
  41.         /*
  42.          * second solution: using String format and printf
  43.          */
  44.         // for each row
  45.         for (int row = 0; row < n; row += 1) {
  46.             // build string of spaces
  47.             String spc = row == 0 ? "" : String.format("%" + row + "s", " ");
  48.             // build string of asterisks
  49.             String ast = n == row ? "" : String.format("%" + (n - row) + "s",
  50.                     " ").replace(" ", "*");
  51.  
  52.             // print the row
  53.             System.out.printf("%s%s\n", spc, ast);
  54.         }
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement