Note: This is homework/assignment feel not to answer if you don't want to.
Ok after some search and reading these:
How to check if array element is null to avoid NullPointerException in Java
Gracefully avoiding NullPointerException in Java
http://c2.com/cgi/wiki?NullPointerException
Am still not making any progress on how to deal with NullPointerException error on my code, snippet for questionable code:
int findElement(String element) {
int retval = 0;
for ( int i = 0; i < setElements.length; i++) {
if ( setElements[i].equals(element) ) { // This line 31 here
return retval = i;
}
else {
return retval = -1;
}
}
return retval;
}
void add(String newValue) {
int elem = findElement(newValue);
if( numberOfElements < maxNumberOfElements && elem != -1 ) {
setElements[numberOfElements] = newValue;
numberOfElements++;
} else { System.out.println("Element " + newValue + "already exist"); }
}
It compile but adding new element to a set throws a NullPointerException error.
D:\javaprojects>java SetDemo
Enter string element to be added
A
You entered A
Exception in thread "main" java.lang.NullPointerException
at Set.findElement(Set.java:31)
at Set.add(Set.java:44)
at SetDemo.main(Set.java:145)
I added another check, though honestly don't have clue if this right to line 31.
if ( setElements != null && setElements[i].equals(element) ) but still no joy.
A documentation/tips or explanation is greatly appreciated.
learning,
lupin
Did you initialize setElements anywhere? Meaning:
String[] setElements = new String[100];
If you simply declare an array variable:
String[] setElements;
as a data member of your class it is initialized to null. You have to make it point to something. You can either do this inline:
public class MyClass {
private String[] setElements = new String[100];
...
}
or in a constructor:
public class MyClass {
private String[] setElements;
public MyClass() {
setElements = new String[100];
}
...
}
The for-loop in findElement doesn't make sense.
for ( int i = 0; i < setElements.length; i++) {
if ( setElements[i].equals(element) ) { // This line 31 here
return retval = i;
}
else {
return retval = -1;
}
}
You should iterate through all values before returning -1, only then do you know that there is no element in the set that matches element.
Post the entire class - this snippet is useless.
You're making two serious mistakes: failing to believe the compiler, and assuming that your code is correct.
If the JVM tells you that line 31 is the problem, believe it.
My guess is that setElements[i] is null.
It should be setElements[i] != null && setElements[i].equals(element). If a collection contains null elements you will try to dereference a null reference when you call equals method on that element.
As for NullPointerException - you should never catch it. For things that shouldn't be null, they must be initialized properly. For those things that cannot be null - they must be checked for null before dereferencing them (i.e. calling methods on them).
The only use case for catching NullPointerException is when you are using a third-party library that you don't have the source for and has a bug that causes NullPointerException to be thrown. These cases are rare and since you only beginning to learn Java, forget that I mentioned this and concentrate on more important things.
Try testing the element itself for null, not the array:
setElements[i] != null && setElements[i].equals(element)
You should not attempt to catch a null pointer exception. Instead, the best way to avoid null pointers is:
In any function that takes parameters where you assume that the parameter is non-null, always check that the parameter is non-null and throw an IllegalArgumentException if it is null.
Whenever you invoke a function that does not allow null parameters, ensure that you do not pass a null pointer to that function; if you already know that the object is non-null (because you already checked it and would have thrown an IllegalArgumentException), then you do not need to recheck; otherwise, you should double-check that the object is non-null before passing it along.
Since you do not check the parameters to your findElement and add functions, it is quite possible that the parameters are the culprits. Add the appropriate check and throw IllegalArgumentException if they are null. If, after you do that, you get an IllegalArgumentException, then you've solved your problem. If not, then you at least know that the problem is not the parameter and is elsewhere in the code.
Its working now, thanks to Lars,Igor and the rest who took time to critic the code, there's a logic error that wasn't check,anyway here's the corrected working code, lastly I'm bother am I doing cheating? :(
int findElement(String element) {
int retval = 0;
for ( int i = 0; i < setElements.length; i++) { //loop first to the array and only return -1 once we can't find it.
//setElements[i] != null is the NullPointerException killer :)
if ( setElements[i] != null && setElements[i].equals(element) ) {
return retval = i;
}
retval = -1;
}
return retval;
}
void add(String newValue) {
int elem = findElement(newValue);
if( numberOfElements < maxNumberOfElements && elem == -1 ) { # == instead of != as I only need to add if elements is non-existing
setElements[numberOfElements] = newValue;
numberOfElements++;
}
}
with thanks,
lupin
Related
I'm fairly new to Java and I'm using BlueJ. I keep getting this "Int cannot be dereferenced" error when trying to compile and I'm not sure what the problem is. The error is specifically happening in my if statement at the bottom, where it says "equals" is an error and "int cannot be dereferenced." Hope to get some assistance as I have no idea what to do. Thank you in advance!
public class Catalog {
private Item[] list;
private int size;
// Construct an empty catalog with the specified capacity.
public Catalog(int max) {
list = new Item[max];
size = 0;
}
// Insert a new item into the catalog.
// Throw a CatalogFull exception if the catalog is full.
public void insert(Item obj) throws CatalogFull {
if (list.length == size) {
throw new CatalogFull();
}
list[size] = obj;
++size;
}
// Search the catalog for the item whose item number
// is the parameter id. Return the matching object
// if the search succeeds. Throw an ItemNotFound
// exception if the search fails.
public Item find(int id) throws ItemNotFound {
for (int pos = 0; pos < size; ++pos){
if (id.equals(list[pos].getItemNumber())){ //Getting error on "equals"
return list[pos];
}
else {
throw new ItemNotFound();
}
}
}
}
id is of primitive type int and not an Object. You cannot call methods on a primitive as you are doing here :
id.equals
Try replacing this:
if (id.equals(list[pos].getItemNumber())){ //Getting error on "equals"
with
if (id == list[pos].getItemNumber()){ //Getting error on "equals"
Basically, you're trying to use int as if it was an Object, which it isn't (well...it's complicated)
id.equals(list[pos].getItemNumber())
Should be...
id == list[pos].getItemNumber()
Dereferencing is the process of accessing the value referred to by a reference . Since, int is already a value (not a reference), it can not be dereferenced.
so u need to replace your code (.) to(==).
Assuming getItemNumber() returns an int, replace
if (id.equals(list[pos].getItemNumber()))
with
if (id == list[pos].getItemNumber())
Change
id.equals(list[pos].getItemNumber())
to
id == list[pos].getItemNumber()
For more details, you should learn the difference between the primitive types like int, char, and double and reference types.
As your methods an int datatype, you should use "==" instead of equals()
try replacing this
if (id.equals(list[pos].getItemNumber()))
with
if (id.equals==list[pos].getItemNumber())
it will fix the error .
I think you are getting this error in the initialization of the Integer somewhere
try
id == list[pos].getItemNumber()
instead of
id.equals(list[pos].getItemNumber()
Now when as[i].getUser() = null, the program stops with NullPointerException. But what I want is to stop the current process of the loop only and continue with next value, the best will be from the method convertUser() since it's used in many places. I know that catching the NullPointerException is not recommended.
public Project[] convertProjects(){
ProjectR[] as = getProjects();
Project[] bs = new Project[a.length];
for(int i = 0; i < as.length; i++){
Project b = new Project();
b.setName(as[i].getNameR());
b.setUser(convertUser(as[i].getUserR()));
b.setCenter(convertCenter(as[i].getCenterR()));
bs[i]=b;
}
return bs;
}
private Center convertCenter(CenterR centerR) {
Center centerL = new Center();
centerL.setManager(convertUser(centerR.getUser()));
centerL.setName(centerR.getName());
centerL.setResID(centerR.getID());
return centerL;
}
private User convertUser(UserR uR) {
User userL = new PFPWSUser();
userL.setID(uR.getID());
userL.setFirstName(uR.getFirstName());
userL.setLastName(uR.getLastName());
userL.setEmail(uR.getEmail());
return userL;
}
Add these two lines
as[i] == null
continue;
b.setUser(convertUser(as[i].getUserR()));
inside your convertProjects Method
Check if as[i].getUserR() is null before using it:
if(as[i].getUserR() != null) { // Can use since not null
b.setUser(convertUser(as[i].getUserR()));
}
Since no null values are used, the NullPointerException wont be thrown and the loop will continue.
insert checking element as[i] for null
if (as[i]==null) continue;
at start of for{} block
I have a method that is suppose to traverse 2 arrays of Ojbects, the first being Menu of size 50, which contains Recipes, which hold up to 10 elements called ingredients, which holds up to 3 elements each, but I am only looking for their names! I want to take the matching names of those Ingredient elements in the Recipes and add them to my String array and then return it, here is my code...
public class Recipe implements Cloneable
{
String Name;
final int INGREDIENT_ARRAY_MAX = 10;
Ingredient Ingredients[] = new Ingredient[INGREDIENT_ARRAY_MAX];
public class RecipeBook
{
final static int MENU_ARRAY_MAX = 50;
static Recipe Menu[] = new Recipe[MENU_ARRAY_MAX];
public static String[] getRecipesByIngredient(String ingredientName)
{
String[] targetRecipes = new String[MENU_ARRAY_MAX];
int counter = 0;
for (int j = 0; j < Menu.length; j++)
{
if (Menu[j] == null)
{
break;
}
else
{
for (int k = 0; k < Menu[j].Ingredients.length; k++)
{
System.out.println(Menu[j].Ingredients[k]);
if (Menu[j].Ingredients[k].getName().equals(ingredientName))
{
targetRecipes[counter] = Menu[j].getName();
counter++;
}
}
}
}
return targetRecipes;
}
}
}
Now I know it doesn't work and why, but the solution I am not sure about. At the moment I only have 3 Recipes and 3 Ingredients in each recipe! The stuff up top is just for reference, those are the object arrays of RecipeBook (Menu) and Recipes (Ingredients).
Now when ran this code gets me into a NullPointerException because tries testing nulls against Strings, but how could I make it check through the Recipe, if it doesn't find anything, it moves on to the next Recipe in Menu, if it does, it simply adds it but continues to check til finish. I tried adding "if" statements checking for nulls and not nulls but it becomes convoluted and it still doesn't get my program to return to checking the rest of the arrays. I know the first "if" can stay because, well if the spot i check in Menu is null, the rest of it must be null so there's no point in going farther. But how do I check the Ingredients array, find something, add it, and go back to sifting through the Menu for recipes with that ingredient? Is it possible to add an if inside the inner loop to check for null and if it is, just go back to the outer loop?
update if conditions as below
1st if condition :
if (Menu[j] == null || Menu[j].Ingredients == null || Menu[j].Ingredients.length ==0)
2nd if condition :
if (Menu[j].Ingredients[k] != null && ingredientName.equal(Menu[j].Ingredients[k].getName()))
please let me know if there any issues.
I don't know how you fill the recipe array but what i can say is that your code is missing a lot of null checks. I would go this way (code not compiled / tested):
public static String[] getRecipesByIngredient(String ingredientName) {
String[] targetRecipes = null;
// check input parameter ingredientName against null and do lookup only if it is not null
if(ingredientName != null) {
// init the result array and do look up
targetRecipes = new String[MENU_ARRAY_MAX];
for (int j = 0; j < Menu.length; j++) {
// you might run into NPE if Menu[j] or if the array of ingredients in Menu[j] (Menu[j].Ingredients) is null
if(Menu[j] != null && Menu[j].Ingredients != null) {
for (int k = 0; k < Menu[j].Ingredients.length; k++) {
// Menu[j].Ingredients[k] may also be null
// Menu[j].Ingredients[k].getName() may also be null but no need to check it since
// you call equals of the string object ingredientName witch you already checked
// and equals(null) is always false in that case
if (Menu[j].Ingredients[k] != null && ingredientName.equals(Menu[j].Ingredients[k].getName()) {
// here you might want to check Menu[j].getName() against null otherwise you'll have
// a null inside your result array (this is some like a land mine) unless you want
// to check against null while iterating over you result array
if(Menu[j].getName() != null) {
targetRecipes[counter++] = Menu[j].getName();
}
}
}
} // save the else...
}
} // else targetRecipes is still null, with witch you may want to say "no result found"
return targetRecipes;
}
I have the following code snippet.
Explanation:
I have the array called result.
This array consists of different String attributes like "city", "countryName" and "IATA".
With a for loop, I try to access and retrieve all the aforementioned fields.
My problem now is: While "city" and "countryName" always have a value, "IATA" sometimes does not have a value and thus returning me "null", which leads to the nullPointerException as soon as I access an empty "IATA".
I tried this:
if(entry.getIATA().equals(null)) {
} else {
startIATA[count] = entry.getIATA();
}
But, this if condition is not working as I try to access a field which is null.
Has anyone an idea how I can solve this?
Here is the relevant code snippet:
private String[] startIATA = new String[200]; //That is more than long enough
...
for (int count = 0; count < result.getAirports().length(); count++) {
AirportsEntry entry = result.getAirports().get(count);
// Block for StartAirport
HorizontalPanel hp = new HorizontalPanel();
hp.setSpacing(5);
hp.add(new Label(entry.getCity()));
hp.add(new Label(entry.getCountryName()));
hp.add(new Label(entry.getIATA()));
GWT.log("IATA: " + entry.getIATA());
if(entry.getIATA().equals(null)) {
} else {
startIATA[count] = entry.getIATA();
}
startAirportVP.add(hp);
}
Thank you very much for your time and your help!
Perform a simple null check prior to accessing the property of the object.
if(entry != null && entry.getIATA() != null){
startIATA[count] = entry.getIATA();
}
You cannot use equals method to check for null. Use ==:
if (entry.getIATA () == null)
use this:
if (entry.getIATA() != null)
I trying to find whether the elements of 2 arrayLists are match or not.
But this code give me error Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException since some of the elements are null.
How can I solved this problem?
String level []={"High","High","High","High","High","High"};
ArrayList<Object> n = new ArrayList<Object>(Arrays.asList(level));
String choice []={null,"High","Low","High",null,"Medium"};
ArrayList<Object> m = new ArrayList<Object>(Arrays.asList(choice));
//Check if the two arrayList are identical
for(int i=0; i<m.size(); i++){
if(!(m.get(i).equals(n.get(i)))){
result= true;
break;
}
}
return result;
}
Just use Arrays.equals, like so:
String level []={"High","High","High","High","High","High"};
String choice []={null,"High","Low","High",null,"Medium"};
return Arrays.equals(level, choice);
The problem is that you are calling the equals method on some elements without first checking for null.
Change to:
for(int i=0; i<m.size(); i++){
if(m.get(i) != null && !(m.get(i).equals(n.get(i)))){
result = true;
break;
}
}
Or if you want to allow two null values to compare equal:
for(int i=0; i<m.size(); i++){
if (m.get(i) == null) {
if (n.get(i) != null) {
result = true;
}
} else if(!(m.get(i).equals(n.get(i)))){
result = true;
}
if (result) {
break;
}
}
One thing I don't get - why are you setting result to true when you find a mismatch? Don't you want to return true if both lists match and false otherwise?
The root of this problem could be you are using null as an actual value.
Just looking at your code you could use enum and instead of null use an EMPTY value. Then you can actually compare with in a list without nullpointerexceptions.
Check this out:
http://java.sun.com/docs/books/tutorial/java/javaOO/enum.html
Also try to avoid using arrays. Just use List but use the proper type. Don't use List<Object> that is almost never valid.
null should indicate an error or testing only. It should never be used in valid code as you will create null pointer exception bugs during runtime.
if you know the first list never contains nulls switch the call around
if(!(n.get(i).equals(m.get(i)))){
also specifying ArrayList<Object> is bad practice, use List<String> if it is actually String objects.
Check if the objects are the same object (or both null) first. Check for null before you do the equals() test.
boolean result = true;
String level[] = { "High", "High", "High", "High", "High", "High" };
ArrayList<String> n = new ArrayList<String>(Arrays.asList(level));
String choice[] = { null, "High", "Low", "High", null, "Medium" };
ArrayList<String> m = new ArrayList<String>(Arrays.asList(choice));
// Check if the two arrayList are identical
for (int i = 0; i < m.size(); i++) {
String mElement = m.get(i);
String nElement = n.get(i);
if (mElement == nElement) {
result = true;
} else if ((mElement == null) || (nElement == null)) {
result = false;
break;
} else if (!(m.get(i).equals(n.get(i)))) {
result = false;
break;
}
}
return result;
}
Rewrite your if like this in order to check for both double-nullity and single-nullity:
if((m.get(i) == null && n.get(i) == null) || (m.get(i) != null && !(m.get(i).equals(n.get(i)))))
Rather than solving this specific problem, give yourself a tool you can use over and again, e.g.:
public static final boolean areEqual(Object o1, Object o2) {
return o1 == null ? o2 == null : o1.equals(o2);
}
...in some handy utility class, then use that in your loop.
But of course, for this specific requirement, derivation has the right answer (use java.util.Arrays.equals(Object[],Object[])).
Remove NULLs
You can remove NULL values from your List objects before processing.
myList.removeAll( Collections.singleton( null ) );
The Collections class is a bunch of convenient utility methods. Not to be confused with Collection (singular), the interface that parents List and is implemented by ArrayList.
See this posting, Removing all nulls from a List in Java, for more discussion.