need help!

import java.util.*;

public class Test {

protected String name;

protected String second;

protected String last;

protected void setFirstName(String name){

this.name=name;

}

protected void setSecondName(String a){

second=a;

}

protected void setLastName(String a){

last=a;

}

protected String getName(){

return name;

}

protected String getSecond(){

return second;

}

protected String getLast(){

return last;

}

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

Test[] a = new Test[3];

for(int i=0;i<3;i++){

System.out.println("Enter first name: ");

a.setFirstName(scan.nextLine());

System.out.println("Enter second name:");

a.setSecondName(scan.nextLine());

System.out.println("Enter last name");

a.setLastName(scan.nextLine());

}

for(int i=0;i<3;i++){

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

System.out.println(a.getSecond());

System.out.println(a.getLast());

}

}

}

Why, when I start the program and enter the first name to the console it throws a NullPointerException?

[1287 byte] By [androa] at [2007-11-26 23:58:25]
# 1

> ...

> Why, when I start the program and enter the first

> name to the console it throws a

> NullPointerException?

Because after doingTest[] a = new Test[3];

your array is filled with null's. You should doa[0] = new Test();

a[0].setSomething(...);

...

Or do it like this:Test[] a = {new Test(), new Test(), new Test()};

A couple of tips for future postings:

- use a discriptive message title, just "help" is worthless;

- use code tags when posting code: http://forum.java.sun.com/help.jspa?sec=formatting

- copy and paste the exact compiler/runtime errors.

Good luck.

prometheuzza at 2007-7-11 15:46:16 > top of Java-index,Java Essentials,Java Programming...
# 2

Test[] a = new Test[3];

...

// "a" is an array...

a.setFirstName(scan.nextLine());

// you should put this instead:

a[i].setFirstName(scan.nextLine());

Kind regards!

igor_ba at 2007-7-11 15:46:16 > top of Java-index,Java Essentials,Java Programming...
# 3
Your code should not even have compiled.. You are using "a." when "a" is an array.. It should not be possible..
anandaraja84a at 2007-7-11 15:46:16 > top of Java-index,Java Essentials,Java Programming...
# 4

> Test[] a = new Test[3];

> ...

>

> // "a" is an array...

> a.setFirstName(scan.nextLine());

> // you should put this instead:

> a[i].setFirstName(scan.nextLine());

>

> Kind regards!

No, the [i] got interpreted as an italic tag by the forum software. The array a does not hold any instances of Test objects, that's why the NPE is being thrown.

prometheuzza at 2007-7-11 15:46:16 > top of Java-index,Java Essentials,Java Programming...
# 5
> Your code should not even have compiled.. You are> using "a." when "a" is an array.. It should not be> possible..See my previous reply.
prometheuzza at 2007-7-11 15:46:16 > top of Java-index,Java Essentials,Java Programming...