Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package class170629;
- import java.util.Scanner;
- public class LoopsEx04Slide66 {
- public static void main(String[] args) {
- // input: integer number.
- // output: triangle aligned to right
- // create a scanner
- Scanner s = new Scanner(System.in);
- // ask for input
- System.out.print("Enter an integer number: ");
- // get and save input value
- int n = s.nextInt();
- // close scanner
- s.close();
- /*
- * first solution: printing single char every time
- */
- // for each row
- for (int row = 0; row < n; row += 1) {
- // print spaces first
- for (int spc = 0; spc < row; spc += 1) {
- System.out.print(" ");
- }
- // print asterisks
- for (int ast = 0; ast < n - row; ast += 1) {
- System.out.print("*");
- }
- // end of the line
- System.out.println();
- }
- /*
- * second solution: using String format and printf
- */
- // for each row
- for (int row = 0; row < n; row += 1) {
- // build string of spaces
- String spc = row == 0 ? "" : String.format("%" + row + "s", " ");
- // build string of asterisks
- String ast = n == row ? "" : String.format("%" + (n - row) + "s",
- " ").replace(" ", "*");
- // print the row
- System.out.printf("%s%s\n", spc, ast);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement