NoSuchElementException when using scanner to read input
The following Java method is supposed to take a string (person's name) from the user using the keyboard, find that name in an array with a name, name[]
and remove that name from the array (by assignment name[i] = "INVALID"
).
The code is trying to accept an input string (person's name) using a class object Scanner
del_name
, but I am getting NoSuchElementException
in the statement
s=del_name.next();
ie 4th operator from the top.
I would be very grateful if someone can provide a solution and also explain why this code is not working. (Thank)
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();
}
source to share
Change .next()
to .nextLine()
.
Scanner del_name=new Scanner(System.in);
String s;
System.out.println("Enter the name to be deleted");
s=del_name.nextLine();
Scanner.next () returns the same as the current input, even if there isn't one (giving you your error). Scanner.nextLine () skips the current line and returns the missing part.
source to share
Try,
del_name.nextLine()
Usage next()
will only return what comes before the space. nextLine()
automatically moves the scanner down after returning the current line.
next():
Finds and returns the next complete token from this scanner.
nextLine():
Adapts this scanner to the current line and returns the input that was skipped.
source to share
The code you posted does not throw an exception as it is. You may have done something before this call to the method that called it. As proof, run this code:
public class Test {
static String[] name = new String[] {"AAA", "BBB", "CCC"};
static void deletee() {
Scanner delName = new Scanner(System.in);
System.out.println("Enter the name to be deleted");
String s = delName.next();
boolean found = false;
for (int i = 0; i < name.length; i++) {
if (name[i].equalsIgnoreCase(s)) {
name[i] = "INVALID";
System.out.println("Deletion Successful");
found = true;
break;
}
}
if (!found)
System.out.println("No such person exist");
delName.close();
}
public static void main(String[] args) {
deletee();
for (int i = 0; i < name.length; i++)
System.out.print(name[i] + ", ");
}
}
Notes
- Method names must begin with lowercase.
- Non-final variables should not use underscores, only the top lines where a new word begins.
- I rewrote the search engine to be something more intuitive, although there are many more ways to do this.
- Nice job when closing the scanner.
source to share