Results 1 to 13 of 13
Like Tree1Likes
  • 1 Post By jim829

Thread: Need Help with a NullPointerException

  1. #1
    Doghouse is offline Member
    Join Date
    Mar 2015
    Posts
    10
    Rep Power
    0

    Default Need Help with a NullPointerException

    I need some help figuring out why I'm getting a NullPointerException on this. I am posting the code that contains the error.

    The errors are in the method call

    sortArray(slist);

    and

    for(int test = index + 1; test < len; test++)

    Java Code:
    import java.util.Scanner;
    
    public class ShapeDemo
    {
        /**
         * getShape - read a Shape's description and create the specific object
         */
        public static Shape getShape()
        {
            Scanner sc = new Scanner(System.in);
    
            // Continue asking for input until a valid shape entered, or 'done'
            do {
                System.out.println("\nEnter the shape's color (or 'done')...");
                String color = sc.nextLine();
                if (color.equalsIgnoreCase("done")) {
                    return null;
                }
                if (!color.equalsIgnoreCase("red") &&
                    !color.equalsIgnoreCase("blue") &&
                    !color.equalsIgnoreCase("green")) {
                    System.out.println("  Error - color must be 'red', 'blue', or 'green'");
                    continue;
                }
    
                System.out.println("Enter shape type...");
                String name = sc.nextLine();
                if (name.equalsIgnoreCase("circle")) {
                    System.out.println("Enter the radius...");
                    double radius = sc.nextDouble();
                    if (radius < 0.0) {
                        System.out.println("Radius must be non-negative");
                        continue;
                    }
                    return new Circle(color, radius);
                } else if (name.equalsIgnoreCase("rectangle")) {
                    System.out.println("Enter the length and width...");
                    double length = sc.nextDouble();
                    double width = sc.nextDouble();
                    if (length < 0.0 || width < 0.0) {
                        System.out.println("length and width must be non-negative");
                        continue;
                    }
                    return new Rectangle(color, length, width);
                } else if (name.equalsIgnoreCase("square")) {
                    System.out.println("Enter the length of a side...");
                    double length = sc.nextDouble();
                    if (length < 0.0) {
                        System.out.println("length must be non-negative");
                        continue;
                    }
                    return new Square(color, length);
                } else {
                    System.out.println("shape name must be 'circle', 'rectangle', or 'square'");
                    continue;
                }
            } while (true);
    
        }
    
        /**
         * main
         */
        public static void main (String[] args)
        {
            Scanner sc = new Scanner(System.in);
    
            // Create an array of Shape references larger than the maximum number
            // of Shapes to be read (could also prompt for size).
            Shape[] slist = new Shape[50];
    
            // Read shapes until null returned. Note that this code doesn't know what
            // specific type of Shape has been returned.
            System.out.println("Enter a list of shapes - 'done' to end");
            Shape sp;
            int numShapes = 0;
            while (null != (sp = getShape())) {
                slist[numShapes++] = sp;
            }
    
            // Print the list of shapes. Get the specific Shape's information using
            // dynamic binding to call the implementation of toString() defined for
            // the actual type of Shape referenced.
            System.out.println("\nThe list of shapes entered...");
            for (int n = 0; n < numShapes; ++n) {
                System.out.println("  " + slist[n].toString());
            }
    
            // Sort the list of shapes into ascending order by area. Get the each
            // specific shape's area using dynamic binding to call the implementation
            // of area() defined for the the actual type of Shape referenced.
            System.out.println("\nSorting shapes into order by area...");
            
    
            sortArray(slist); // error  Exception in thread "main" java.lang.NullPointerException
    
            // Print the sorted list of shapes.
            System.out.println("\nThe sorted list of shapes...");
            for (int n = 0; n < numShapes; ++n) {
                System.out.println("  " + slist[n].toString());
            }
    
            // Keep console window alive until 'enter' pressed (if needed).
            System.out.println();
            System.out.println("Done - press enter key to end program");
            String junk = sc.nextLine();
        }
    
    
        public static void sortArray(Shape [] list)
        {
            //simple selection sort method to sort array in ascending order
            int len = list.length;
            for(int index = 0; index < len; index++)
            {
                for(int test = index + 1; test < len; test++)
                {
                    if(list[index].area() > list[test].area()) 
    				// error  Exception in thread "main" java.lang.NullPointerException
                    {
                        Shape temp;
                        temp = list[index];
                        list[index] = list[test];
                        list[test] = temp;                   
                    }
                }
            }
        }
    }

  2. #2
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    12,059
    Rep Power
    26

    Default Re: Need Help with a NullPointerException

    Quote Originally Posted by Doghouse View Post
    I need some help figuring out why I'm getting a NullPointerException on this. I am posting the code that contains the error.
    Also post the stack trace.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  3. #3
    Doghouse is offline Member
    Join Date
    Mar 2015
    Posts
    10
    Rep Power
    0

    Default Re: Need Help with a NullPointerException

    Please forgive me, I'm not sure how to do that. I am VERY new to Java.

  4. #4
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: Need Help with a NullPointerException

    My guess would be that when you print out the shapes you are using a counter. When you try to sort them you are using the actual length of the array which is 50. Unless you populated the entire array with shapes, some of those entries will be null.

    Regards,
    Jim
    gimbal2 likes this.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  5. #5
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    5,114
    Rep Power
    12

    Default Re: Need Help with a NullPointerException

    just for reference, when you get an exception it will looks something like this:

    Java Code:
    Exception in thread "main" java.lang.NullPointerException   // the exception
            at Test.sortArray(Test.java:17)                            // the stacktrace
            at Test.main(Test.java:12)
    The "stacktrace" part of the exception tells which methods of which classes were invoked to reach the point of error; whenever you post about an exception always post the stacktrace too because that is usually far more informative than the exception message.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  6. #6
    Doghouse is offline Member
    Join Date
    Mar 2015
    Posts
    10
    Rep Power
    0

    Default Re: Need Help with a NullPointerException

    I added some code to track the variables and got this result:

    Enter the shape's color (or 'done')...
    red
    Enter shape type...
    circle
    Enter the radius...
    5

    Enter the shape's color (or 'done')...
    blue
    Enter shape type...
    square
    Enter the length of a side...
    2

    Enter the shape's color (or 'done')...
    green
    Enter shape type...
    rectangle
    Enter the length and width...
    2
    3

    Enter the shape's color (or 'done')...
    done

    The list of shapes entered...
    red circle with radius 5.0 with area 78.53981633974483
    blue square with length 2.0 with area 4.0
    green Rectangle with length 2.0 and width 3.0 with area 6.0

    Sorting shapes into order by area...
    list[index].area(): 78.53981633974483
    list[test].area(): 4.0
    list[index].area(): 4.0
    list[test].area(): 6.0
    list[index].area(): 4.0
    Exception in thread "main" java.lang.NullPointerException
    at shape.ShapeDemo.sortArray(ShapeDemo.java:144)
    at shape.ShapeDemo.main(ShapeDemo.java:117)
    Java Result: 1

    It appears that the problem is with the second half of the if statement on the last itteration. I tried replacing len with len -1 but got the same error.

  7. #7
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: Need Help with a NullPointerException

    Did you read my reply? You are only entering three shapes.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  8. #8
    Doghouse is offline Member
    Join Date
    Mar 2015
    Posts
    10
    Rep Power
    0

    Default Re: Need Help with a NullPointerException

    Yes, I read your comment, I thought that the loop would end when index < len and the inner loop when test < len, where len = list.length

  9. #9
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    26

    Default Re: Need Help with a NullPointerException

    Quote Originally Posted by jim829 View Post
    Did you read my reply? You are only entering three shapes.

    Regards,
    Jim
    ...out of 50.

    So what do you think those other 47 entries in your array have in them?

    (sorry for hijacking, Jim)
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  10. #10
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: Need Help with a NullPointerException

    Quote Originally Posted by Doghouse View Post
    Yes, I read your comment, I thought that the loop would end when index < len and the inner loop when test < len, where len = list.length
    Actually, if that were the case, the loop would never run since index starts out as 0 so it is immediately < 50. If you are as new to Java as you say your are, perhaps you should try some more basic programs.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  11. #11
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    5,114
    Rep Power
    12

    Default Re: Need Help with a NullPointerException

    Clearly mister Doghouse doesn't have much experience yet with doing simple debugging tricks - so why are we not trying to teach him?

    It all goes wrong in that sortArray() method - you've already figured that out because of the exception stacktrace. So rather than staring at the code trying to guess, give yourself more information to work with. Add some more System.out.println() statements and print out the values of the different variables used there. That should quickly show you where what you expect and what is reality differ from each other.

    Debugging is partly a mental game - you have to teach yourself to stop thinking "Why is Java doing this to me" and start thinking "okay where did I goof". You achieve the latter by basically opening up and exposing the guts of your application; dig around and find that faulty wire / leaking pipe. Then patch it.

    Debugging is also a game of investing time to save yourself time; that is a hump which is not easy to cross for many people. To not have too much information on the screen, in this case I would comment out some of the print statements you already have that are part of your main program. Limit the amount of information you see to what is relevant to you to solve the problem.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  12. #12
    benji2505 is offline Senior Member
    Join Date
    Sep 2014
    Location
    MA, USA
    Posts
    399
    Rep Power
    6

    Default Re: Need Help with a NullPointerException

    checking for a null value beforehand should do the trick.

  13. #13
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,995
    Rep Power
    9

    Default Re: Need Help with a NullPointerException

    Quote Originally Posted by benji2505 View Post
    checking for a null value beforehand should do the trick.
    You cannot slap an if (blah != null) { ... } around any variable that produces a NullPointerException. Sometimes a value CAN be null (expected), and sometimes it's NOT supposed to be null. You'll then need to find out WHY it's null instead of surrounding it with if != null.

    When you come to the point where you write code like this, you should find the address of the nearest library and get a book about Visual Basic. Especially study the On Error Resume Next....
    Java Code:
    try {
       doMyStuff();
    }
    catch( NullPointerException e) {
      //ignore
    }
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

Similar Threads

  1. NullPointerException
    By MiiNiiW in forum New To Java
    Replies: 1
    Last Post: 02-06-2014, 03:24 PM
  2. NullPointerException
    By kai555 in forum JDBC
    Replies: 10
    Last Post: 08-25-2011, 11:18 AM
  3. NullPointerException
    By donchini in forum New To Java
    Replies: 4
    Last Post: 05-20-2010, 01:11 AM
  4. NullPointerException help me!
    By phancuong87 in forum New To Java
    Replies: 4
    Last Post: 01-19-2010, 04:01 PM
  5. Why do I get a NullPointerException?
    By nessa203 in forum New To Java
    Replies: 5
    Last Post: 01-07-2010, 01:14 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •