"名称" class nullpointerexception;试图重做代码

时间:2016-06-17 16:29:15

标签: java class nullpointerexception stringbuffer

我看过"什么是NullPointerException以及如何解决?"虽然这个问题及其答案根本没有帮助。我理解我的问题; " NameTest"程序试图引用"名称"对象虽然它为null,但我不知道如何修改它来修复它,因为我希望所有" Name"可以访问lastName,firstName和fullName。方法。在"名称"程序,我试图创建一个" Name"用于创建空白名称对象的类,然后使用setName()方法分配String / Stringbuffer值(具体取决于哪个更好)。这是"姓名"代码:

public class Name
{
private StringBuffer lastName;
private StringBuffer firstName;
private StringBuffer fullName;

public Name()
{
    lastName.replace( 0, 0, "" );
    firstName.replace( 0, 0, "" );
    fullName.replace( 0, 0, "" );
}

public Name( String lN, String fiN )
{
     lastName.replace( 0, lN.length() - 1, lN );

     firstName.replace( 0, fiN.length() - 1, fiN );     

     fullName.replace( 0, (lastName.length() + firstName.length()) + 2, lastName + ", " + firstName);
}

public Name( String fuN )
{
    String[] fuNTemp = fuN.split( ", " );
    lastName.replace( 0, fuNTemp[0].length() - 1, fuNTemp[0] );
    firstName.replace( 0, fuNTemp[1].length() - 1, fuNTemp[1] );

    fullName.replace( 0, (lastName.length() + firstName.length()) + 2, lastName + ", " + firstName);
}

public void setName( String n )
{
    String[] nTemp = n.split( ", " );
    lastName.replace( 0, nTemp[0].length() - 1, nTemp[0] );
    firstName.replace( 0, nTemp[1].length() - 1, nTemp[1] );

    fullName.replace( 0, (lastName.length() + firstName.length()) + 2, lastName + ", " + firstName);
}

public void setName( String lN, String fiN )
{
    lastName.equals( lN );
    firstName.equals( fiN );

    fullName.equals( lastName + ", " + firstName );
} 

public StringBuffer getName()
{
    return fullName;
}
}

这是程序" NameTest",我创建的只是为了帮助弄清楚"姓名":

public class NameTest
{
public static void main( String [] args )
{
    Name test = new Name();

    System.out.println( test.getName() );
    System.out.println();

    String Doe = new String( "Doe" );
    String John = new String( "John" );

    test.setName( Doe, John );

    System.out.println( test.getName() );
}
}

以下是来自" NameTest"的错误消息:

Exception in thread "main" java.lang.NullPointerException
    at Name.<init>(Name.java:9)
    at NameTest.main(NameTest.java:5)

2 个答案:

答案 0 :(得分:0)

您尚未初始化StringBuffer变量的值。默认它将具有null值,并且在构造函数中,您尝试使用字符串“”替换null值。这导致NullPointerException。

初始化StringBuffer变量。

private StringBuffer lastName=new StringBuffer("lastName");
private StringBuffer firstName=new StringBuffer("firstName");
private StringBuffer fullName=new StringBuffer("fullName");

答案 1 :(得分:0)

NullPointerException课程中的Name正在发生,因为当您的值为null时,您正尝试访问它。值为null,因为这是非原始变量类型的默认值。 N K Raju在他的Google网站上有很好的tutorial数据类型。

要解决您的问题,请在构造函数中使用它们之前初始化lastNamefirstNamefullName变量。

没有参数的示例:

public Name() {
    lastName = new StringBuffer();
    firstName = new StringBuffer();
    fullName = new StringBuffer();
}

参数示例:

public Name(String lN, String fiN) {
   lastName = new StringBuffer(lN);
   firstName = new StringBuffer(fiN);
   fullName = new StringBuffer(lN + ", " + fiN);
}