I'm trying to implement a phonebook in Java with ArrayLists but whenever I try to get user info using either next() or nextLine() I get errors. This is the method that collects and saves the user input.
public void saveContact() {
String[] userInput = new String[3];
String[] input = {"name", "age", "phone number"};
String[] pattern = {".", "\\d", ".+\\d+"};
for(int i=0; i < 3; i++) {
try (Scanner sc = new Scanner(System.in)) {
String name = "";
while(!verifyUserInput(name, pattern[i])) {
System.out.printf("Enter contact's %s\n", input[i]);
name = sc.nextLine();
userInput[i] = name;
}
}
}
phoneArrayList.add(userInput);
}
Whenever I use nextLine() I get
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
at PhoneDirectory.saveContact(PhoneDirectory.java:42)
at MainClass.main(MainClass.java:19)
And when I use next() I get
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 PhoneDirectory.saveContact(PhoneDirectory.java:42)
at MainClass.main(MainClass.java:19)
I've tried using hasNext() and hasNextLine() like this but it just results in an infinite loop. I have no idea what I'm supposed to use to get user input without having errors.
if(sc.hasNext()) {
name = sc.next();
}
And this is the verifyUserInput method
public boolean verifyUserInput(String input, String patt) {
Pattern pattern = Pattern.compile(patt);
Matcher m = pattern.matcher(input);
return m.find();
}