-1
public class X {
// some fields
private Route[] tabT = new Route[50]; // [1]

public String toString() {
    int i;
    String descT = "";
    for (i = 0; i < tabT.length; i++)
        descT += tabT[i].toString();
    String description;
    description = "MESSAGE " + lastName
            + "\nMESSAGE " + firstName
            + "\nMESSAGE " + year
            + "\nMESSAGE " + address
            + "\nMESSAGE " + number
            + "\nMESSAGE " + descT
            + "\n";
    return description;
}

我的类包含一些字段,包括来自另一个类的对象列表tabT。在toString()方法中,我想显示这些字段和另一个对象的字段,但我不知道为什么它会显示错误。当我在元素上创建标签时,它不会显示错误。

Exception in thread "main" java.lang.NullPointerException
    at Chauffeur.toString(Chauffeur.java:38)
    at java.lang.String.valueOf(String.java:2854)
    at java.io.PrintStream.println(PrintStream.java:821)
    at AutoSuperieur.main(AutoSuperieur.java:6)

正好在这条线上descT += tabT[i].toString();

4

2 回答 2

0
if (tabT != null) 
  descT += (tabT[i] == null?"":tabT[i].toString());

To make sure you understand it how it works. You've got NullPointerException in the toString(). Then you should check what variable could be null value. After editing your question I see that tabT is initialized, so the if (tabT != null) check is not nessesary but it protect the code above from the NullPointerException because in the second line I use reference tabT that might not been initialized. Next the operator [] dereferncing the elements of the array that could be null value. The ternary operator ? checks that value and if it's null then returns "" otherwise toString() the value of the element. To make this call possible the value should not be null. Then I use grouping () to return the result string to the concatenate operator += that incrementally concatenates old and new values.

于 2013-03-10T22:56:18.623 回答
0

您可以使用String.valueOf()来处理空值。

descT += String.valueOf(tabT[i]);

此外,操作员+=执行复制(至少在一般情况下)。您应该更好地使用StringBuilder来处理大连接。

于 2013-03-10T23:05:00.760 回答