Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package class170629;
- import java.util.Scanner;
- public class LoopsEx05Slide67 {
- public static void main(String[] args) {
- // input: integer number.
- // output: triangle of asterisks
- // 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();
- // for each row
- for (int row = 1; row <= n; row += 1) {
- // print asterisks on the left
- for (int ast = 0; ast < row; ast += 1) {
- System.out.print("*");
- }
- // print spaces first
- for (int spc = 0; spc < 2 * (n - row); spc += 1) {
- System.out.print(" ");
- }
- // print asterisks on the right
- for (int ast = 0; ast < row; ast += 1) {
- System.out.print("*");
- }
- // end of the line
- System.out.println();
- }
- System.out.println();
- /*
- * second solution: using String format and printf
- */
- // for each row
- for (int row = 1; row <= n; row += 1) {
- // build string of asterisks
- String ast = String.format("%" + row + "s", " ").replace(" ", "*");
- // build string of spaces
- String spc = row == n ? "" : String.format("%" + 2 * (n - row)
- + "s", " ");
- // print the row
- System.out.printf("%s%s%s\n", ast, spc, ast);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement