Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 7 of 7

Thread: problem in java.lang.NullPointerException

  1. #1
    Junior Member
    Join Date
    Jul 2010
    Posts
    3
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default problem in java.lang.NullPointerException

    hello, im new in java..><
    import java.util.Scanner;
     
    public class Book {
            private String author, title;
            private int year;
            private Chapter first,second,third;
            public Book(){
                author="";
                title="";
                year=0;
                first=null;
                second=null;
                third=null;
            }
            public String getAuthor(){
                return author;
            }
     
            public String getTitle(){
                return title;
            }
            public int getYear(){
                return year;
            }
            public void printInfo(){
                System.out.println("Book title: "+getTitle());
                System.out.println("Book author: "+getAuthor());
                System.out.println("Year: "+getYear());
                System.out.println("Total number of pages: "+totalPages());
     
            }
            private int totalPages(){
              return  first.getPages()+second.getPages()+third.getPages();
           }
     
            public void PrintContents(){
                System.out.println("Chapter 1:");
                System.out.println("  Title: "+first.getTitle());
                System.out.println("  Nuber of pages: "+first.getPages());
                System.out.println("Chapter 2:");
                System.out.println("  Title: "+second.getTitle());
                System.out.println("  Number of pages: "+second.getPages());
                System.out.println("Chapter 3:");
                System.out.println("  Title: "+third.getTitle());
                System.out.println("  Number of pages: "+third.getPages());
     
            }
            public void inputInfo(){
                Scanner scan=new Scanner(System.in);
                System.out.println("Please enter the book's title");
                title=scan.next();
                System.out.println("Please enter the book's author");
                author=scan.next();
                System.out.println("Please enter the book's year");
                year=scan.nextInt();
            }
     
    }

    import java.util.Scanner;
     
    public class Chapter {
            private String title;
            private int numberOfPages;
            public Chapter(){
                title="";
                numberOfPages=0;
            }
            public String getTitle(){
                return title;
            }
            public int getPages(){
                return numberOfPages;
            }
     
            public void input(){
                Scanner scan=new Scanner(System.in);
                System.out.println("Please enter the chapter title");
                title=scan.next();
                System.out.println("Please enter the number of pages");
                numberOfPages=scan.nextInt();
            }
     
    }

    public class Main {
     
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
           Chapter first=new Chapter();
           first.input();
           Chapter second=new Chapter();
           second.input();
           Chapter third=new Chapter();
           third.input();
           Book b=new Book();
           b.inputInfo();
           b.printInfo();
           b.PrintContents();
        }
     
    }

    this is my output

    Book title: smile
    Book author: yea
    Year: 2010
    Exception in thread "main" java.lang.NullPointerException
    at a2q1.Book.totalPages(Book.java:39)
    at a2q1.Book.printInfo(Book.java:35)
    at a2q1.Main.main(Main.java:26)

    how to fix the error??help me pls...T.T
    Last edited by jianghuzai; July 28th, 2010 at 05:13 AM.


  2. #2
    Member
    Join Date
    Jul 2010
    Posts
    45
    Thanks
    10
    Thanked 3 Times in 3 Posts

    Default Re: problem in java.lang.NullPointerException

    Just from a quick glance, it looks like the Book class' private Chapter reference variables never actually point to anything. They are initialized to null in the constructor and they never point to anything.

    The Chapter objects created in the main function are not the same as the private variables in the Book class object.

  3. #3
    Junior Member
    Join Date
    Jul 2010
    Posts
    3
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: problem in java.lang.NullPointerException

    oo...
    erm...wat code i nid to change/edit??
    will let the Chapter variables(in the Book class) are point to the chapter class's
    Last edited by jianghuzai; July 28th, 2010 at 07:14 AM.

  4. #4
    Member
    Join Date
    Jul 2010
    Posts
    45
    Thanks
    10
    Thanked 3 Times in 3 Posts

    Default Re: problem in java.lang.NullPointerException

    If you insist on designing it the way you are, I guess the quickest and simplest fix would be something like this:

    public static void main(String[] args) {
    Book b=new Book();
     
    b.first=new Chapter();
    b.first.input();
     
    b.second=new Chapter();
    b.second.input();
     
    b.third=new Chapter();
    b.third.input();
     
    b.inputInfo();
    b.printInfo();
    b.PrintContents();
    }

    Of course you'd also need to change Book's Chapter reference variables to public (or if they are in the same package you could also use the default access modifier or protected):

    public class Book {
          ....
           [B] public Chapter first,second,third;[/B]
           ...
    }

    The way that you have created the Book class makes it very limited. Every book created can only have 3 chapters. If I was making it, I would add another constructor to Book that takes an argument to specify the number of chapters and have an array of Chapters:

    public class Book {
     
    private int numChapters;
    private Chapter[] chap;
     
    public Book(){
    this(1); //Calls the other constructor
    }
     
    public Book (int numChapters){
    ...
    this.numChapters = numChapters;
    chap = new Chapter[numChapters];
     
    for(int i=0; i<numChapters; i++)
    chap[i] = new Chapter();
    ...
    }

    I haven't tried compiling any of this, just a couple of ideas off the top of my head.
    Last edited by bbr201; July 28th, 2010 at 07:53 AM.

  5. The Following User Says Thank You to bbr201 For This Useful Post:

    jianghuzai (July 28th, 2010)

  6. #5
    Junior Member
    Join Date
    Jul 2010
    Posts
    3
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: problem in java.lang.NullPointerException

    hahaa...yea..it s work...thx u very much...=D
    but..u give me the suggestion...erm...
    actually im not really understand in "this" keyword..XDXD
    "this" keyword has any features??coz im newbie in java..><
    ps: i was search the "this" keyword in google n i see their explanation, now still not understand..XDXD

  7. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,166
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: problem in java.lang.NullPointerException

    "this" is a reference variable that has the address of the class object that is currently being executed.
    You know what object reference variables are? 'this' is one like the others.
    AClass aClassReference = new aClass(); //Define and initialize a reference to a class object
    Here aClassReference is a reference to a aClass object.
    You would code: aClassReference.aVariable to reference a variable in that class.
    You use "this" to reference class variables in the current class being executed.
    this.aVariable references the variable: aVariable in the current class.

  8. #7
    Member
    Join Date
    Jul 2010
    Posts
    45
    Thanks
    10
    Thanked 3 Times in 3 Posts

    Default Re: problem in java.lang.NullPointerException

    Here are some examples of how you might use it:

    class A{
    [B]int value;[/B]
    public A([B]int value[/B]){
    this.value = value;
    }
    }

    You can see that the constructor has one parameter named value. But the class also has a member variable named value. They both have the same name.

    In this situation, the class member will be hidden. In other words, if you are inside the constructor and just refer to value, you are referring to the parameter. In order to refer to the class member, you would need to qualify it with this, as in this.value.

    Alternatively, you could have something like this:

    class A{
    [B]int value;[/B]
    public A([B]int val[/B]){
    value = val;
    }
    }

    In this case, the class member isn't hidden because the parameter has a different name. So, when you refer to value, you are referring to the class member. And of course when you refer to val you are referring to the parameter. This way is not preferred because you have to give a different name for the parameter and class member and it could get confusing when they are supposed to represent the same thing.

    Another use of this is like this:

    class B{
     
    public B(){
    this(5);
    }
     
    public B(int value){
    //do something here....
    }
    }

    Here this is used by one constructor to call another constructor within the same class. I believe it has to be the first line in the constructor code.

    So if you create a new B object like this:

    B test = new B();

    The first (parameterless) constructor will be called. The first (and only) line of code in this constructor calls the second constructor which expects an argument of type int.

    The reason that one constructor calls another is generally to save yourself from repeating the same code.

    For example, consider this class:

    class C{
    String name;
    int age;
     
    public C(){
    name = "John";
    age = 15;
    }
    public C(String name, int age){
    this.name = name;
    this.age = age;
    }
    }

    Alternatively, you could save yourself from having to initialize the member variables more than once by having one constructor call another.

    class C{
    String name;
    int age;
     
    public C(){
    this("John", 15);
    }
    public C(String name, int age){
    this.name = name;
    this.age = age;
    }
    }

    Creating multiple constructors (or methods) with the same name but different numbers and/or types of parameters is called overloading the constructor (or method). The compiler chooses which one to call based on the number and/or type of arguments.

    Finally, let's say you are calling a method that expects one argument of type E:

    void someMethod (E obj)

    You can pass the current instance of the object from within the class by using this:

    class E{
    public void test(){
    someMethod(this); //When this code is executed, pass the invoking object as an argument
    }
    }

    So if you create two E objects in your code like this:
    E first = new E();
    E second = new E();

    first.test(); //In this case, someMethod will receive a reference to the object referred to by first
    second.test(); //In this case, someMethod will receive a reference to the object referred to by second

    I hope that clears things up a little bit!
    Last edited by bbr201; July 28th, 2010 at 10:36 AM.