gpt4 book ai didi

java - 无法弄清楚为什么我在数组打印语句中得到空值

转载 作者:行者123 更新时间:2023-12-02 06:35:11 24 4
gpt4 key购买 nike

我正在加载一个数组,从它周围的值中获取总和,然后根据 sum/6 的值将一个字符串值分配给一个新数组。因此,当我运行它时,每个数组值都应该包含一些内容,而不是空值。但是,当我打印数组时,我得到了预期的输出(基于我给出的示例),但打印语句中的随机“null”除外。我不明白为什么会出现这些空语句。这是我的代码以及打印内容和应该打印内容的示例。

public static void displaymap(int maparray[][])
{
String mapicons[][] = new String [22][32];
int col=1;
int row=1;
int row2=0;
int col2=0;
double sum[]= new double [704];
for(int i=0;i<704;i++)
{
if(col ==33)
{
col = 1;
row++;
if(row==24)
{
row=0;
col=0;
break;
}
}
sum[i]=(double)(maparray[row][col]+maparray[row-1][col]+maparray[row+1][col]+maparray[row][col-1]+maparray[row][col+1])/6;
col++;
System.out.printf("%.2f\n",sum[i]);
if(sum[i]>9)
{
mapicons[row2][col2]=" #";
}
if(sum[i]>8&&sum[i]<9)
{
mapicons[row2][col2]=" *";
}
if(sum[i]>7&&sum[i]<8)
{
mapicons[row2][col2]=" +";
}
if(sum[i]>6&&sum[i]<7)
{
mapicons[row2][col2]=" .";
}
if(sum[i]<6)
{
mapicons[row2][col2]=" ";
}
col2++;
if(col2 ==32)
{
col2 = 0;
row2++;
}
}
for(row=0;row<22;row++)
{
for(col=0;col<32;col++)
System.out.printf("%s",mapicons[row][col]);
System.out.println();
}
}

这是正在输出的内容:

                              null         .                      
null # null
null . + . . +
. +null null . + . .
. .
+ . .null null
+ . null .
+ .null + .
. null . . . null
. . . .
. null +
nullnull
. . . . . .
. nullnull
.null
null . . .
. . . + . null
null null
. .
. + . .
null . . . . . null
. . * . .

这就是应该输出的内容:

                                       .                      
#
. + . . +
. + . + . .
. .
+ . .
+ . .
+ . + .
. . . .
. . . .
. +

. . . . . .
.
.
. . .
. . . + .

. .
. + . .
. . . . .
. . * . .

正如您所看到的,它本质上是相同的东西减去空值,并且如果没有空值占用空间,某些字符将正确格式化。

最佳答案

有一些边缘情况您的代码无法处理。没有条件为 true,因此 mapicons 未完全填充。然后,null 值被打印出来。

例如,当 sum 恰好等于 8、7 或 6 时。

尝试使用以下代码:

public static void displaymap(int maparray[][])
{
String mapicons[][] = new String [22][32];
int col=1;
int row=1;
int row2=0;
int col2=0;
double sum[]= new double [704];
for(int i=0;i<704;i++)
{
if(col ==33)
{
col = 1;
row++;
if(row==24)
{
row=0;
col=0;
break;
}
}
sum[i]=(double)(maparray[row][col]+maparray[row-1][col]+maparray[row+1][col]+maparray[row][col-1]+maparray[row][col+1])/6;
col++;
System.out.printf("%.2f\n",sum[i]);
if(sum[i]>=9)
{
mapicons[row2][col2]=" #";
}
else if(sum[i]>=8)
{
mapicons[row2][col2]=" *";
}
else if(sum[i]>=7)
{
mapicons[row2][col2]=" +";
}
else if(sum[i]>=6)
{
mapicons[row2][col2]=" .";
}
else
{
mapicons[row2][col2]=" ";
}
col2++;
if(col2 ==32)
{
col2 = 0;
row2++;
}
}
for(row=0;row<22;row++)
{
for(col=0;col<32;col++)
System.out.printf("%s",mapicons[row][col]);
System.out.println();
}
}

编辑:您甚至可以使用 if/elseif 代替 if 链。

关于java - 无法弄清楚为什么我在数组打印语句中得到空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19735210/

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