This is class Main. There are two more classes in the models(Contact, ContactManager) and a txt file(contact.txt) I have tried to load contacts from contacts.txt. This program was working and now it is not. I can not find the mistake or how can I fix this unchecked exception. If I have to throw NoSuchElementException, where I have to add this?
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.text.ParseException;
import java.util.Scanner;
import models.Contact;
import models.ContactManager;
class Main {
static ContactManager manager = new ContactManager();
public static void main(String[] args) {
try {
loadContacts("contacts.txt");
System.out.println("CONTACTS LOADED\n\n");
System.out.println(manager);
manageContact();
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
}
}
public static void loadContacts(String fileName) throws FileNotFoundException {
FileInputStream fis = new FileInputStream(fileName);
Scanner scan = new Scanner(fis);
while (scan.hasNextLine()) {
try {
Contact contact = new Contact(scan.next(), scan.next(), scan.next());
manager.addContact(contact);
} catch (ParseException e) {
System.out.println(e.getMessage());
}
}
scan.close();
}
public static void manageContact() {
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("Would you like to a) add another contact b) remove a contact c) exit");
String response = scan.nextLine();
if (response.equals("a")) {
System.out.println("\tName: ");
String name = scan.nextLine();
System.out.println("\tPhone number: ");
String phoneNumber = scan.nextLine();
System.out.println("\tBirth Date: ");
String birthDate = scan.nextLine();
if (name.isBlank() || phoneNumber.isBlank() || phoneNumber.length() < 5) {
System.out.println("\nThe input is not valid.");
} else {
try {
manager.addContact(new Contact(name, phoneNumber, birthDate));
} catch (ParseException e) {
System.out.println(e.getMessage());
} finally {
System.out.println("\n\nUPDATED CONTACTS\n\n" + manager);
}
}
} else if (response.equals("b")) {
System.out.println("Who would you like to remove?");
manager.removeContact(scan.nextLine());
System.out.println("\n\nUPDATED CONTACTS\n\n" + manager);
} else {
break;
}
}
scan.close();
}
}
This program was working and now it is not. I can not find the mistake or how can I fix this unchecked exception.
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1478)
at Main.loadContacts(Main.java:28)
at Main.main(Main.java:14)`
How to fix this NoSuchElementException? Would you mind helping me to understand what is wrong?