字符串在打印时一直说null,即使其中有数据



我在这段代码中生成一个字符串,然后应用一个子字符串。

String input = "AnyString"
for(int i = 0; i < input.length(); i++)
//i tracks which line we are on when printing the triangle
{
int tracker = 0;
for(int j = 0; j < line.length(); j++)
//j tracks which "column of the line" we are currently on
{
if(i + 1 == input.length()
//If we are on the the last line of the triangle
|| Math.abs(j - line.length()/2) == i)
//or if the column we are on is i letters away from the center
{
outputs[i] += line.charAt(j);
out.println("Outputs has been updated with:n"+line.charAt(i));
out.println("nAnd it is now:n"+outputs[i]);
tracker = j;
//tracker will keep track of what the position of the last letter was
}else{
out.println("Outputs has been updated with: a space");
out.println("nAnd it is now: "+outputs[i]);
outputs[i] += " ";
}
}
//Where the substring is applied
}

当它为第一个循环运行时,输出为:

输出已更新为:一个空格

现在是:null

有什么想法吗?为什么字符串说它是空的,尽管我在打印前已经在空格中添加了它?我刚刚注意到,在输出上,在它说null之前有一个空格。目前,我将声明从字符串中删除单词null,但如果有人能提出一个不那么迟钝的解决方案,我将不胜感激

感谢大家的时间和关注!

打印输出来自else分支。

在设置了outputs[i]else之上没有代码路径,因此其值为null

您在print语句或outputs[i] += " ";中都没有得到NullPointerException,因为这两个语句处理null值的方式有一个怪癖。

CCD_ 7和串联总是对它们的自变量执行CCD_。在这两种情况下,空字符串值都将变为字符串"null"

最新更新