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

String keeps saying null on print even though it has data in it

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

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
}

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

输出已更新为:space

现在是:null

知道为什么即使我在打印前在 space 中添加了字符串,但它仍显示为空吗?我刚刚注意到,在输出中,在它表示 null 之前有一个 space。现在,我将声明从字符串中删除 null 一词,但如果有人能提出一个不那么迟钝的解决方案,我将不胜感激。

感谢大家的时间和关注!

打印输出来自 else 分支。

设置了outputs[i]else上面没有代码路径,所以它的值为null.

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

println 和串联总是对它们的参数做 String.valueOf()。在这两种情况下,空字符串值都变成字符串 "null".