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