The following Java method is suppose to accept a string (name of a person) from the user via keyboard, search that name in an array called name[]
and delete that person's name from the array (by assigning name[i] = "INVALID"
).
The code tries to accept the input string (the name of the person) using a Scanner
class object del_name
, but I am getting a NoSuchElementException
in the statement
s=del_name.next();
i.e the 4th statement from the top.
I will be really grateful if someone can give a solution and also explain as to why this code is not working. (Thank You)
void Deletee()
{
Scanner del_name=new Scanner(System.in);
String s;
System.out.println("Enter the name to be deleted");
s=del_name.next(); // causing NoSuchElementException
int i=0;
/* find position in which the name occurs using while-loop below */
while(!s.equalsIgnoreCase(name[i]) && i<count)
i++ ; // increment i to search in next array index
if(i<count)
{
name[i]="INVALID";
count--;
System.out.println("Deletion Successful");
}
else
{
System.out.println("No such person exist");
}
del_name.close();
}