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 hình vuông (square star pattern). Mẫu được tạo bằng nhiều vòng lặp for lồng nhau và lệnh in.
Minh họa
Đầu vào:
Enter the length of a side : 8
Đầu ra:
The square pattern : * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Thuật toán
- Bắt đầu
- Khai báo 3 số nguyên:
i,j,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 SquarePattern {
public static void main(String args[]) {
int i, j, my_input;
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 length of a side : ");
my_input = my_scanner.nextInt();
System.out.println("The square pattern : ");
for (i = 1; i <= my_input; i++) {
for (j = 1; j <= my_input; j++) {
System.out.print("*");
}
System.out.print("\n");
}
}
}
Đầu ra
Required packages have been imported A reader object has been defined Enter the length of a side : 8 The square pattern : * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Ví dụ 2: Giá trị định nghĩa trước
public class SquarePattern {
public static void main(String args[]) {
int i, j, my_input;
my_input = 8;
System.out.println("The length of a side is defined as " + my_input);
System.out.println("The square pattern : ");
for (i = 1; i <= my_input; i++) {
for (j = 1; j <= my_input; j++) {
System.out.print("* ");
}
System.out.print("\n");
}
}
}
Đầu ra
The length of a side is defined as 8 The square pattern : * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *