gpt4 book ai didi

java - 在java中用二维数组绘制数字钻石

转载 作者:行者123 更新时间:2023-11-30 10:53:11 25 4
gpt4 key购买 nike

所以我需要在 Java 中使用二维数组制作一个菱形外观的数字。我得到了我的结果,但在钻石之前是空的。对于 drawNumDiamond(9),我必须得到一个一直到 5 并返回的钻石外观。我知道我可以在不使用数组的情况下做到这一点,但我想了解有关二维数组的更多信息:this is how it should look like and what are my results

public class Example1{
private static void drawNumDiamond(int h) {

if(h%2 != 0) {
int size = h/2 +1;
int count = 1;
int loop = 1;
String[][] dijamant = new String[h][];
for(int row = 0; row < dijamant.length; row++) {

dijamant[row] = new String[row+1];

for(int kolona=0; kolona<=row; kolona++) {

dijamant[0][0] = "1";

for(int i=0; i< loop;i++) {

dijamant[row][kolona]+= count;

}

}
count++;
loop+=2;

}

for (int k = 0; k < size; k++) {
System.out.printf("%" + h + "s", dijamant[k]);
h++;
System.out.println();
}
h--;
for (int q = size - 2; q>=0; q--) {
h--;
System.out.printf("%" + h + "s", dijamant[q]);
System.out.println();
}

}
}
public static void main(String[] args) {

drawNumDiamond(9);

}
}

最佳答案

问题出在这一行:

dijamant[row][kolona] += count;

如果 dijamant[row][kolona]null 并且 count 为 2,则字符串连接的结果将为 “null2”。尝试在使用空字符串初始化之前添加以下 if 语句:

if (dijamant[row][kolona] == null) {
dijamant[row][kolona] = "";
}

这将使您的代码正常工作,但仍有一些事情需要考虑。例如。你一直在循环中设置 dijamant[0][0] = "1";

关于java - 在java中用二维数组绘制数字钻石,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34108972/

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