1.实心三角形

代码:

 import java.util.Scanner;

 public class Test {

     public static void main(String[] args) {
int rows;
Scanner sc = new Scanner(System.in);
System.out.println("Please input rows:");
rows = sc.nextInt();
sc.close();
for (int i = 1; i <= rows; i++) {//控制打印行数
for (int j = 1; j <= rows - i; j++) {//控制每行打印空格数
System.out.print(" ");
}
for (int j = 1; j <= i * 2 - 1; j++) {//控制打印星号数
System.out.print("*");
}
System.out.println();//每打一行,换行
}
} }

2.空心三角形

代码:

 import java.util.Scanner;

 public class Test {
public static void main(String[] args) {
int rows;
Scanner sc = new Scanner(System.in);
System.out.println("Please input rows:");
rows = sc.nextInt();
sc.close();
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= rows - i; j++) {
System.out.print(" ");
}
for (int j = 1; j <= 2 * i - 1; j++) {
if (i == 1 || i == rows) { // 如果是第一行或最后一行,打印所有星号
System.out.print("*");
} else if (j == 1 || j == 2 * i - 1) { // 如果是每行的第一个或者最后一个,打印星号
System.out.print("*");
} else { // 其余打印空格
System.out.print(" ");
}
}
System.out.println();
}
}
}

3.实心菱形

代码:

 import java.util.Scanner;

 public class Test {
public static void main(String[] args) {
int rows;
Scanner sc = new Scanner(System.in);
System.out.println("Please input odd rows:");// 只能是奇数行
rows = (sc.nextInt() + 1) / 2;// 上半部分行数
sc.close();
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= rows - i; j++) {
System.out.print(" ");
}
for (int j = 1; j <= 2 * i - 1; j++) {
System.out.print("*");
}
System.out.println();
}
for (int i = rows - 1; i >= 1; i--) { // 下半部分不可重复打印上半部分最后一行,i=rows-1)
for (int j = 1; j <= rows - i; j++) {
System.out.print(" ");
}
for (int j = 1; j <= 2 * i - 1; j++) {
System.out.print("*");
}
System.out.println();
}
}
}

4.空心菱形

代码:

 import java.util.Scanner;

 public class Test {
public static void main(String[] args) {
int rows;
Scanner sc = new Scanner(System.in);
System.out.println("Please input odd rows:");// 只能是奇数行
rows = (sc.nextInt() + 1) / 2;// 上半部分行数
sc.close();
sc.close();
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= rows - i; j++) {
System.out.print(" ");
}
for (int j = 1; j <= 2 * i - 1; j++) {
if (i == 1) {
System.out.print("*");
} else if (j == 1 || j == 2 * i - 1) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println();
}
for (int i = rows - 1; i >= 1; i--) {// 此处只需i=rows-1即可
for (int j = 1; j <= rows - i; j++) {
System.out.print(" ");
}
for (int j = 1; j <= 2 * i - 1; j++) {
if (i == 1) {
System.out.print("*");
} else if (j == 1 || j == 2 * i - 1) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
}
05-27 09:01