I have written one simple program in which there is a string array which contains names.
This program searches for the name given by the user in the string array. If it is present, then it says name found otherwise not found.
When the I’m giving the name, i.e. already present in the string, then the program is working perfectly, but when I’m giving the name i.e. is not present in the string it shows the error.
import java.util.Scanner;
class Work {
Scanner in = new Scanner(System.in);
String e_name;
String name[]=new String [50];
void getname()
{
System.out.println("enter the name");
e_name=in.nextLine();
}
int search()
{
System.out.println("name to be searched"+" "+e_name);
for(int i=0;i<name.length;i++){
if(name[i].equals(e_name))
return i;
}
return -1;
}
}
public class Array {
public static void main(String args[])
{
Work ob1=new Work();
int search_res;
ob1.name[0]="aditya";
ob1.name[1]="ankit";
ob1.getname();
search_res=ob1.search();
System.out.println(search_res);
if(search_res!=-1)
{
System.out.println("name found");
}
else if (search_res==-1)
{
System.out.println("name not found");
}
}
}
error
enter the name
manoj
Exception in thread "main" java.lang.NullPointerException
at Work.search(Array.java:24)
at Array.main(Array.java:56)
name to be searched manoj
You’re iterating over every value in the
namearray. That array looks like this:So for the first two iterations, it’ll be fine – but after that, when i is 2, this line:
will be calling
equalsonnull, hence the exception.Leaving aside any issues about encapsulation, good design etc, the cleanest fix for this particular problem would be to use a
List<String>:Then these lines:
would become:
And your loop would become:
Alternatively, you could stick with an array, and just reverse the equality check:
Given that
e_namewill never be null (with the way you’re running it), this will never throw an exception. It’s still odd to have a hard-coded number of names though – aList<String>would be a better solution.