'NoSuchElementException error in console input [duplicate]
The program sends an email to a recipient. The recipient is requested from simple DB by ID or offered to input a new email.
log.info("Enter ID: ");
while (true) {
if (scanner.hasNextLong()) {
long id = scanner.nextLong();
if (id > 0 || id < recipientDaoList.size()) {
return recipientDao.getById(id);
} else {
log.info("ID is not valid! Try again ");
scanner.nextLong();
}
}
}
I have a lot of console requests in my program and after scanner.nextLong() request (asking ID recipient) follows scanner.nextLine() request (asking an email theme).
if (recipient.getId() > 0 && recipient.getId() < recipientDaoList.size()) {
log.info("You're going to send a letter to " + recipient.getEmail());
inputFields.setRecipientEmail(recipient.getEmail());
try (Scanner scanner = new Scanner(System.in)) {
log.info("Theme of the letter:");
inputFields.setTheme(scanner.nextLine());
log.info("Main text of the letter:");
inputFields.setText(scanner.nextLine());
return inputFields;
}
}
The exception throws after the request of the email theme
I use the try-with-resources statement everywhere when create Scanner object. I tried to delete the ID request and to put (and return) just any long instead. In this case the exception disappears. It seems that the exception throws because scanner.nextLong() is before scanner.nextLine(). Is there anyone who has experienced this?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
