getting a java.lang.NullPointerException Error

Discussion in 'Scripting & Programming' started by Pheonicks56, Feb 2, 2009.

  1. Pheonicks56

    Pheonicks56 Kilobyte Poster

    364
    6
    49
    Alright so my program compiled fine but I end up getting java.lang.NullPointerException as an error. What am I doing wrong? I get the same error at two locations, Line 183
    Code:
    if(array[b].compareTo(array[b+1])>0)
    and line 144
    Code:
    sortString(arrayName, arrayName.length);
    Code:
    import java.util.Arrays;
    import java.text.NumberFormat;
    import java.io.*;
    
    public class DVD
    {
        // Declaration of variables
        int done = 1, i;
        double productNumber = 0;
        double unitsInStock = 0;
        double unitPrice = 0;
        double inventoryValue = 0;
        double totalInventoryValue = 0;
        double arrayProductNumber[] = new double[10];
        double arrayUnitsInStock[] = new double[10];
        double arrayUnitPrice[] = new double[10];
        double arrayInventoryValue[] = new double[10];
        String inventory, name, yesorno, next, price, units;
        String arrayName[] = new String[10];
    
        NumberFormat nf = NumberFormat.getCurrencyInstance();
        BufferedReader dataIn = new BufferedReader (new InputStreamReader (System.in));
        
        public DVD() // DVD constructor
        {
            return;
        } // End DVD constructor
    
        public void dvdInfo() throws IOException
    	{        
    		while (inventory != "stop")
    		{
    			i=0;
    			for (i=0; i<=9; i++)
    			{
    				done = 1;
    				while (done == 1)
    				{
    					System.out.print (" Enter product number or stop to quit: ");// allows user to stop program when there are no more product
    						inventory=dataIn.readLine();
    					try
    					{
    						if (inventory.equals("stop"))
    							System.exit(0);
    						else
    						{
    							productNumber=Double.parseDouble(inventory);
    							if (productNumber < 0) throw new NumberFormatException();
    								done = 2;
    							arrayProductNumber[i] = productNumber;
    							productNumber = 0;
    						}
    					}
    					catch (NumberFormatException e)
    					{
    						System.out.println("Please Enter a Positive Value or Stop.");// asks user for a positive number
    						done = 1;
    					}
    				}
    				done = 1;
    				while (done == 1)
    				{
    					System.out.print("Please Enter DVD Title: ");
    						name=dataIn.readLine();
    					System.out.println("You entered " + name + " is this correct?");
    					System.out.print("Enter y for yes and n for no: ");
    						yesorno=dataIn.readLine();
    					if (yesorno.equals("y") || yesorno.equals("Y"))
    					{
    						arrayName[i] = name;
    						name = "0";
    						done = 2;
    					}
    					else if (yesorno.equals("n") || yesorno.equals("N"))
    						done = 1;
    					else
    					{
    						System.out.println("You did not enter y or n Please re-enter");
    						done = 1;
    					}
    				}
    				done = 1;
    				while (done == 1)
    				{
    					System.out.print("What is units in stock? ");//asks user for how many are on hand
    						units=dataIn.readLine();
    					try
    					{
    						unitsInStock=Double.parseDouble(units);
    						if (unitsInStock < 0) throw new NumberFormatException();
    							done = 2;
    						arrayUnitsInStock[i] = unitsInStock;
    						unitsInStock = 0;
    					}
    					catch (NumberFormatException e)
    					{
    						System.out.println("Please Enter a Positive Value.");// asks for a positive number from user
    						done = 1;
    					}
    				}
    			 	done = 1;
    				while (done == 1)
    				{
    					System.out.print("unit price? ");// asks user for the price of the product
    						price=dataIn.readLine();
    					try
    					{
    						unitPrice=Double.parseDouble(price);
    						if (unitPrice < 0)throw new NumberFormatException();
    							done = 2;
    						arrayUnitPrice[i] = unitPrice;
    						unitPrice = 0;
    					}
    					catch (NumberFormatException e)
    					{
    						System.out.println("Please Enter a Positive Value");// asks user for a positive number
    						done = 1;
    					}
    				}
    				done = 1;
    				while (done == 1)
    				{
    					System.out.println ("do you want to enter another product ");
    					System.out.print ("enter y for yes and n for no ");
    						yesorno=dataIn.readLine();
    					if (yesorno.equals("y") || yesorno.equals("Y"))
    						done = 2;
    					else if (yesorno.equals("n")|| yesorno.equals("N"))
    					{
    						i = 10;
    						done = 2;
    					}
    					else
    						System.out.println ("you did not enter y or n please reenter");
    				}
    			}
    			i = 0;
    			sortString(arrayName, arrayName.length);
    			for(i=0; i<=9; i++)
    			{
    				//convert arrays to variable
    				productNumber = arrayProductNumber[i];
    				name = arrayName[i];
    				unitsInStock = arrayUnitsInStock[i];
    				unitPrice = arrayUnitPrice[i];
    
    				//calculations
    				inventoryValue =unitsInStock * unitPrice;
    				arrayInventoryValue[i] = inventoryValue;
    
    				//Prints Results
    				System.out.println("product number is			\t  " + productNumber);
    				System.out.println("product name is  			\t  " + name);
    				System.out.println("units in stock is			\t  " + unitsInStock);
    				System.out.println("units price is   			\t  " + unitPrice);
    				System.out.println("inventory value is			\t" + nf.format(inventoryValue));
    				System.out.println();
    				System.out.print("Press Enter to Continue...");
    					next=dataIn.readLine();
    
    				if (arrayProductNumber[i+1] == 0)
    					i=10;
    
    				totalInventoryValue = totalInventoryValue + inventoryValue;
    			}
    			System.out.println("the total inventory value is \t" + nf.format(totalInventoryValue));
    		}
    	}
        public void sortString(String[] array, int len)
    	{
    		int a,b;
    		String temp;
    		double hold;
    		int sort = len - 1;
    		for(a=0; a<sort; a++)
    			for(b=0; b<sort; b++)
    				if(array[b].compareTo(array[b+1])>0)
    				{
    					temp=array[b];
    					array[b]=array[b+1];
    					array[b+1]=temp;
    					hold=arrayProductNumber[b];
    					arrayProductNumber[b]=arrayProductNumber[b+1];
    					arrayProductNumber[b+1]=hold;
    					hold=arrayUnitsInStock[b];
    					arrayUnitsInStock[b]=arrayUnitsInStock[b+1];
    					arrayUnitsInStock[b+1]=hold;
    					hold=arrayUnitPrice[b];
    					arrayUnitPrice[b]=arrayUnitPrice[b+1];
    					arrayUnitPrice[b+1]=hold;
    				} // End if
    	} // End method sortStrings
    
        public void reset()
    	{
    		i = 0;
    		for(i=0; i<=9; i++) //erase arrays stored data to reset
    		{
    			arrayProductNumber[i] = 0;
    			arrayName[i] = "0";
    			arrayUnitsInStock[i] = 0;
    			arrayUnitPrice[i] = 0;
    			arrayInventoryValue[i] = 0;
    		}
    	}
    }
     
    Certifications: BSIT, AAIT, A+
    WIP: Network+
  2. dmarsh
    Honorary Member 500 Likes Award

    dmarsh Petabyte Poster

    4,305
    503
    259
    You are trying to access an uninitialised object reference or 'pointer'.

    Readline can return null if the end of stream is reached, are you sure this does not happen ?

    Are there any String, Array or other object derived types that are uninitialised in your program ?

    Have you tried debugging or examining the stack trace ? Normally you can narrow it down to a line number and examine the logic.


    Other advice to consider :-

    Your code is not very Object Orientated, why have Inventory/Stock Control code in a DVD class ? Why not a StockControl class ?

    Its not good procedural code either ! Why not break your code down into manageble meaningful procedures ? For example printDVD(), readDVDInput() etc

    Use scoping rules effectively, not all data needs to be class/object scope. Not all methods / data should be left default scope, declare fields private etc.

    Try not to use 'magic numbers', prefer booleans or enums or other datatypes instead. (Your done flag is confusing.)

    Try to use better control structures and make your logic flow.

    Use library routines instead of your own methods if the standard routines perform the task well, ie sort etc.
     
  3. soundian

    soundian Gigabyte Poster

    1,460
    71
    107
    I think you're probably trying to access an arrayName element that hasn't been initialized yet. Arrays of objects (like Strings) get the default value of null until they are initialized. This means they aren't pointing at anything, hence the null pointer.
    Here probably
    Code:
    sortString(arrayName, arrayName.length);
    for(i=0; [B]i<=9[/B]; i++)
      {
        //convert arrays to variable
        productNumber = arrayProductNumber[i];
        [B]name = arrayName[i];[/B]
        unitsInStock = arrayUnitsInStock[i];
        unitPrice = arrayUnitPrice[i];
    Try i<arrayName.length instead.

    And, use the CODE tags (the # sign on the message toolbar), it'll preserve your indentations and make it easier for people to read.
     
    Certifications: A+, N+,MCDST,MCTS(680), MCP(270, 271, 272), ITILv3F, CCENT
    WIP: Knuckling down at my new job
  4. dmarsh
    Honorary Member 500 Likes Award

    dmarsh Petabyte Poster

    4,305
    503
    259
    Good advice in general, yes do not use hard coded literals like the '9' in 'i<9' if you can avoid it, in fact theres no need to use bounded types like arrays, you could use an ArrayList or similar.

    Yes, please use the [ CODE ] tags !

    One last thing its unlikely indexing outside an array bounds would cause null pointer, Java has ArrayIndexOutOfBoundsException for this purpose.
     
  5. hbroomhall

    hbroomhall Petabyte Poster Gold Member

    6,624
    117
    224
    In my (limited) experience of Java it always gives you a line number in the crash dump.

    That should enable you to pinpoint the problem fairly quickly.

    Harry.
     
    Certifications: ECDL A+ Network+ i-Net+
    WIP: Server+
  6. soundian

    soundian Gigabyte Poster

    1,460
    71
    107
    Good point.If we'd had the line number it would've been easier to find the problem.
     
    Certifications: A+, N+,MCDST,MCTS(680), MCP(270, 271, 272), ITILv3F, CCENT
    WIP: Knuckling down at my new job
  7. Pheonicks56

    Pheonicks56 Kilobyte Poster

    364
    6
    49
    I just updated my OP, hope someone can figure out what I did to jumble this up, after I figure out the errors I am going to clean the code up quite a bit.
     
    Certifications: BSIT, AAIT, A+
    WIP: Network+
  8. dmarsh
    Honorary Member 500 Likes Award

    dmarsh Petabyte Poster

    4,305
    503
    259
    Code:
    String arrayName[] = new String[10];
    Allocates an array for Strings, it does not insert a string in each position in the array it starts off with null references.

    So your sortString method will index into the null values if you enter less than 10 DVD's.
     
  9. soundian

    soundian Gigabyte Poster

    1,460
    71
    107
    A quick fix to check what else you've done would be to add
    Code:
    for(i=0;i<10;i++){
       arrayName[i]="Not set yet!";
    }
    
    into your constructor. That should stop you getting null pointer exceptions.

    Personally, I'd scrap it and start again using three classes:
    Main class: main method containing simple menu system where user can choose to (A)dd, (S)ort, (Q)uit etc
    DVD class: contains variables and methods for each DVD, such as setName, getProductID, getUserInput etc
    Inventory class: contains a list of DVDs and methods to manipulate it, such as displayList, sortList, addDVD etc

    Apart from other problems that dmarsh pointed out you need to look at your variable types. For instance, why is unitsInStock a double? You'll never have .333 of a DVD in stock so make it an int type ,and unless you can foresee stocking more than 32,768 copies of the same DVD make it a short.
    There's two reasons why you should do this, memory and CPU time. Floating point numbers take a bit more number crunching on the CPU's part so integers are quicker to process. A double takes up 8 bytes of memory, a short only 2 bytes, so you use much less RAM.
     
    Certifications: A+, N+,MCDST,MCTS(680), MCP(270, 271, 272), ITILv3F, CCENT
    WIP: Knuckling down at my new job

Share This Page

Loading...
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.