java - 我正在尝试在 Java 中创建菱形
问题描述
我目前有这个代码,它允许我创建菱形的左半部分。有没有办法镜像它来完成右半部分。或者创建这种形状的完全不同的方式。
public class diamond {
int size = 0; //sets a starting value for size
static int length = 9;
public static void main(String[] args) {
//creates half of our diamond shape :(
for (int i = 0; i < length; i++) {
int j = length - 1 - i;
for (int k = length / 2; k < length; k++) {
if (k == i || k == j || k == length + 7 + i - j)
System.out.print("X");
else
System.out.print(" ");
}
System.out.println("");
}
}
}
解决方案
下面的代码根据您的图表打印菱形图案。该程序允许用户输入钻石的行数,还允许用户选择您想要创建钻石的任何形状。
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
int n, i, j, space = 1;
System.out.print("Enter the number of rows: ");
Scanner s = new Scanner(System.in);
n = s.nextInt();
System.out.print("Enter Symbol : ");
char c = s.next().charAt(0);
drawDiamond(n,c);
}
static void drawDiamond(int n, char c) {
int i, j, space, k = 0;
for (i = 1; i <= n; i++) {
for (j = 1; j <= n - i; j++) {
System.out.print(" ");
}
while (k != (2 * i - 1)) {
if (k == 0 || k == 2 * i - 2)
System.out.print(c);
else
System.out.print(" ");
k++;
}
k = 0;
System.out.println();
}
n--;
for (i = n; i >= 1; i--) {
for (j = 0; j <= n - i; j++) {
System.out.print(" ");
}
k = 0;
while (k != (2 * i - 1)) {
if (k == 0 || k == 2 * i - 2)
System.out.print(c);
else
System.out.print(" ");
k++;
}
System.out.println();
}
}
}
样本输出:
Enter the number of rows: 4
Enter Symbol : *
*
* *
* *
* *
* *
* *
*
推荐阅读
- python - 运行任务计划程序任务时如何隐藏窗口
- r - 根据另一列的值更改一列的值
- c - 在头文件中使用 extern 的好处
- typescript - 无法创建可能为 null 类型的 Vue ref
- python - python Django 使用用户注册表单填写自动创建的配置文件模型
- angular - Angular 网站未以正确格式显示日期
- google-apps-script - Google Apps 脚本 hideRow() 停止 for 循环
- javascript - 裁剪部分屏幕共享 WebRTC
- javascript - 使用Javascript查找列表最后一个条目的tabindex,然后从中提取innerText
- javascript - 使用以分钟为单位的偏移量将 utc 时间转换为时区时间 C#