0

I have a list called contacts which accepts objects of type contact. The method i wrote to add a contact to the list always throws the error "java.util.NoSuchElementException: No line found", when the method is called more than once in a row. Apparently the error stems from the line

name = scanner.nextLine();

I hope someone can point out the problem. Thanks in advance.

public void addNewContact() {
    Scanner scanner = new Scanner(System.in);
    String name;
    int number;
    System.out.print("Enter contact name: ");
    name = scanner.nextLine();
    System.out.print("Enter contact number: ");
    number = scanner.nextInt();
    scanner.nextLine();
    Contact contact = new Contact(name, number);
    contacts.add(contact);
    scanner.close();
}
IyadELwy
  • 15
  • 6
  • Here is a similar question with answers. See if it helps you out: https://stackoverflow.com/questions/7209110/java-util-nosuchelementexception-no-line-found – twicelost Dec 01 '20 at 04:23

1 Answers1

-1

All you need to do to fix this, is to remove scanner.close(). Instead of using scanner.close(), you should put the entire function in while(true){..} and use a break; to stop it. You also need to change all of the .nextLine() to .next(). Do not change the .nextInt() This is because .nextLine() is more buggy than .next(). After fixing these two parts, your code should work properly.

Final product:

public void addNewContact() {
  while(true){
    Scanner scanner = new Scanner(System.in);
    String name;
    int number;
    System.out.print("Enter contact name: ");
    //name = scanner.nextLine(); CHANGED
    name = scanner.next();
    System.out.print("Enter contact number: ");
    number = scanner.nextInt();
    Contact contact = new Contact(name, number);
    contacts.add(contact);
    //scanner.close(); REMOVED
    break;
  }
}
FairOPShotgun
  • 125
  • 2
  • 25
  • '`nextLine()` is more buggy'? Specifics please. What bugs? But if he changes `nextLine()` to `next()` his input prompts won't work properly. – user207421 Jun 10 '21 at 01:58
  • If you use two .nextLine() for the same scanner, it won't work. I have tested this. He doesn't need to change it.. but if he wants to use two inputs that ask for Strings.. he might need to use .next() – FairOPShotgun Jun 10 '21 at 11:24