1.任意菱形
//菱形
Scanner myscanner = new Scanner(System.in);
int n = myscanner.nextInt();
for (int i = 0;
i < n / 2 + 1;
i++) {//控制行数
for (int j = 0;
j < n / 2 - i;
j++) {//打印空格
System.out.print(" ");
}
for (int k = 0;
k < 2 * i +1;
k++) {//打印*
System.out.print("*");
}
System.out.println("\n");
}
for (int i = 1;
i < n / 2 + 1;
i++) {
for (int j = 0;
j < i;
j++) {
System.out.print(" ");
}
for (int k = 2 * (n / 2 - i) + 1;
k > 0;
k--) {
System.out.print("*");
}
System.out.println("\n");
}
【java|JAVA 打印菱形】
文章图片
2.空心菱形
方法1
int n;
Scanner myscanner = new Scanner(System.in);
n = myscanner.nextInt();
for (int i = 0;
i < n / 2 + 1;
i++) {//控制行数
for (int j = 0;
j < n / 2 + 1 - i;
j++) {
System.out.printf(" ");
}
for (int k = 0;
k < 2 * i + 1;
k++) {
if (k == 0 || k == 2 * i){//输出第一颗和最后一颗*
System.out.printf("*");
}else System.out.printf(" ");
}
System.out.printf("\n");
//控制换行
}for (int i = n / 2;
i >= 0 ;
i--) {
for (int j = n / 2 - i + 1;
j > 0 ;
j--) {
System.out.printf(" ");
}
for (int k = 0;
k < 2 * i + 1;
k++) {
if (k == 0 || k == 2 * i){//输出第一颗和最后一颗*
System.out.printf("*");
}else System.out.printf(" ");
}
System.out.printf("\n");
}
方法2
Scanner myscanner = new Scanner(System.in);
int n = myscanner.nextInt();
for (int i = -n;
i <= n;
i++) {
for (int j = -n;
j <= n;
j++) {
int k = Math.abs(i) + Math.abs(j);
if (k == n){
System.out.printf("*");
}else {
System.out.printf(" ");
}
}
System.out.println("\n");
}
文章图片
3.边框菱形
Scanner myscanner = new Scanner(System.in);
int n = myscanner.nextInt();
for (int i = -n;
i <= n;
i++) {
for (int j = -n;
j <= n;
j++) {
int k = Math.abs(i) + Math.abs(j);
if (k >= n){
System.out.printf("*");
}else {
System.out.printf(" ");
}
}
System.out.println("\n");
}
文章图片
4.数字菱形
Scanner myscanner = new Scanner(System.in);
int n = myscanner.nextInt();
for (int i = 0;
i < n;
i++) {
int k = 1;
int j;
for (j = 0;
j < Math.abs(n / 2 -i);
j++) {
System.out.printf(" ");
}
for ( j = 0;
j < n - 2 * Math.abs(n / 2 - i);
j++) {
System.out.print(k);
if (j < n / 2 - Math.abs(n / 2 -i)){
k++;
}else {
k--;
}
}
System.out.println("\t");
}
文章图片
推荐阅读
- JAVA|蓝桥杯动态规划这么好理解()
- 蓝桥杯|JAVA 数组专题(韩顺平)
- java|java 逻辑运算符(韩顺平)
- java|java 常用模块_Java 常见面试题的模块
- java|java input 数组_Java基础之(数组)
- java|java web中servlet详解_javaWeb之Servlet详解
- java|测试开发岗面试系列——滴滴面试题
- Elasticsearch|Elasticsearch实战之搜索项目
- kubernetes|2021超全整理,128道kubenetes高频面试题汇总(带答案)