Jump to content

java constructor null pointer exception

- - - - -

  • Please log in to reply
3 replies to this topic

#1
vaironl

vaironl

    Programmer

  • Members
  • PipPipPipPip
  • 117 posts
I asked this question before and people told me I'm not initializing my variables here it is


public class Recipe

{


	private String recipeName,authorName,recipeDescription;

	private String[] ingredientName,units = new String [40];

	private Double[] ingredientAmount = new Double [40];

	private int ratingValue,servingSize;


	public Recipe() // Recipe Constructor example

	{

		recipeName = new String("NONE");

		authorName = new String("NONE");


		for(int setVals =0; setVals<40;setVals++)

		{

			//set values

			ingredientName[setVals] = "";

			units[setVals] = "";

			ingredientAmount[setVals] = 0.0;

		}



		ratingValue= 0;

		servingSize= 0;

		recipeDescription = new String("No Descriptions");

	}

}

There are no syntax errors

#2
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
This
private String[] ingredientName,units = new String [40];
Is the same as:

private String[] ingredientName;

private String[]units = new String [40];
And thus, not the same as:
private String[] ingredientName = new String [40], units = new String [40];


#3
vaironl

vaironl

    Programmer

  • Members
  • PipPipPipPip
  • 117 posts

wim DC said:

This
private String[] ingredientName,units = new String [40];
Is the same as:

private String[] ingredientName;

private String[]units = new String [40];
And thus, not the same as:
private String[] ingredientName = new String [40], units = new String [40];

But the for loop is indeed initializing the variables?

#4
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
Yea, but ingredientName is null. So ingredientName[setVal] will cause a nullpointer.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users