gpt4 book ai didi

java - 控制台中的钻石绘图

转载 作者:行者123 更新时间:2023-12-01 13:38:29 26 4
gpt4 key购买 nike

几天来我一直在解决一个问题,在控制台内绘制一个菱形,要求用户输入,然后根据输入的大小绘制菱形。

我无法在此处绘制菱形,因为格式显示不正确。

我已经能够成功地让钻石的上半部分工作,我认为下半部分会很容易,因为它只是顶部的相反,但是我被困在某些东西上,我似乎无法来弄清楚。

这是我的代码:

import java.util.Scanner;

public class Diamond {

public static void main(String[] args) {

// import the scanner
Scanner scanner = new Scanner(System.in);

// Ask for the number of sides
System.out.println("Enter the diamond size: ");
int sides = scanner.nextInt();

//variables for the diamond
int matrix = sides * 2 + 3;
int midpoint = ((matrix - 1) / 2) + 1;
int mspaces = 0;
int centerSpaces = 0;


// diamond gets made here
for (int rows = 1; rows <= midpoint; rows++) {
int spaces = (sides * 2 + 2) - (sides + rows);
if (rows == 1) {
for (int x = 1; x <= spaces; x++) {
System.out.print(" ");
}
System.out.print("^\n");
}

//top half of the diamond
if (rows > 1 && rows < midpoint) {

if (rows > 2) {
mspaces += 2;
}

for (int x = 1; x <= spaces; x++) {
System.out.print(" ");
}
System.out.print("/");

for (int k = 0; k <= mspaces; k++) {
System.out.print(" ");
}

System.out.print("\\\n");

centerSpaces = mspaces + 2;

}

//center of the diamond
if (rows == midpoint) {
System.out.print("<");
for (int i = 0; i <= centerSpaces; i++) {
System.out.print(" ");
}
System.out.print(">");
}
}

//Bottom half of the diamond
for (int x = midpoint - 1; x <= 1; x--) {

int downSpace = (sides * 2 + 2) - (sides + x);

System.out.println("\n");

if (x == 1) {
for (int y = 1; y <= downSpace; y++) {
System.out.println(" ");
}

if (x > 2) {
mspaces += 2;
}

for (int y = 1; x <= downSpace; y++) {
System.out.print(" ");
}
System.out.print("\\");

for (int k = 0; k <= mspaces; k++) {
System.out.print(" ");
}

System.out.print("/\n");

centerSpaces = mspaces + 2;

}
}

}
}

如果我必须猜测它是什么,它可能是钻石下半部分的 if 语句中的内容,但我不太确定。

编辑:

这是钻石上半部分的屏幕截图:

enter image description here

最佳答案

循环永远不会运行:应该读为 x>=1 (我认为)

for (int x = midpoint - 1; x <= 1; x--)

可能的无限循环:应阅读 y <= downSpace

for (int y = 1; x <= downSpace; y++)

关于java - 控制台中的钻石绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21055090/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com