【发布时间】:2013-03-10 22:54:09
【问题描述】:
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();
【问题讨论】:
-
你能发布更多代码吗?即围绕tabT。它似乎为空。
-
tabT或其元素之一很可能是null。 -
顺便说一句,你不应该使用 String 来连接 man 字符串。你最好使用 StringBuilder
-
@Legend 我改了!
-
为什么不使用 ArrayList 而不是数组?鉴于您的算法,很明显 tabT 数组的某些元素为空。所以你应该在给他们打电话之前检查一下
toString()。
标签: java arrays nullpointerexception tostring