Giới thiệu
Trong bài viết này, chúng ta sẽ tìm hiểu cách in mẫu sao tam giác rỗng vuông góc (hollow right triangle star pattern). Mẫu được tạo bằng nhiều vòng lặp for lồng nhau và lệnh in. Ở dòng đầu in 1 sao, dòng cuối in n sao. Các dòng giữa in 2 sao ở đầu và cuối dòng, giữa là khoảng trắng.
Minh họa
Đầu vào:
Enter the size : 8
Đầu ra:
The hollow pyramid triangle : * ** * * * * * * * * * * ********
Thuật toán
- Bắt đầu
- Khai báo 4 số nguyên:
i,j,k,my_input - Đọc giá trị từ người dùng hoặc định nghĩa trước
- Duyệt 2 vòng lặp
forlồng nhau để tạo khoảng trắng - Sau vòng lặp trong cùng, duyệt thêm vòng
forđể in ký tự - In dòng mới cho các dòng tiếp theo
- Hiển thị kết quả
- Kết thúc
Ví dụ 1: Nhập từ bàn phím (Scanner)
import java.util.Scanner;
public class Hollowtangle {
public static void main(String[] args) {
int my_input, k, i, j;
System.out.println("Required packages have been imported");
Scanner my_scanner = new Scanner(System.in);
System.out.println("A reader object has been defined ");
System.out.print("Enter the size : ");
my_input = my_scanner.nextInt();
for (i = 1; i <= my_input; i++) {
if (i == 1 || i == my_input) {
for (j = 1; j <= i; j++) {
System.out.print("*");
}
} else {
for (j = 1; j <= i; j++) {
if (j == 1 || j == i)
System.out.print("*");
else
System.out.print(" ");
}
}
System.out.println();
}
}
}
Đầu ra
Required packages have been imported A reader object has been defined Enter the size : 8 * ** * * * * * * * * * * ********
Ví dụ 2: Giá trị định nghĩa trước
public class Hollowtangle {
public static void main(String[] args) {
int my_input, i, j;
my_input = 8;
System.out.println("The size is defined as " + my_input);
for (i = 1; i <= my_input; i++) {
if (i == 1 || i == my_input) {
for (j = 1; j <= i; j++) {
System.out.print("*");
}
} else {
for (j = 1; j <= i; j++) {
if (j == 1 || j == i)
System.out.print("*");
else
System.out.print(" ");
}
}
System.out.println();
}
}
}
Đầu ra
The size is defined as 8 * ** * * * * * * * * * * ********