Home > database >  Java scanner used in method setting input to empty string even after a input has been used [closed]
Java scanner used in method setting input to empty string even after a input has been used [closed]

Time:09-28

im trying to make a method which will get the name and number of a new contact and add it to the list of contacts

The code i have written always will set the name variable to "", even if i enter a name. (ive added the nextLine() method to deal with the enter key) the number input works but the name one doesn't here is the method for that:

public static void addContact() {
    System.out.println("Enter new contact name");
    String name = scanner.nextLine();
    scanner.nextLine();
    System.out.println("Enter new contact number");
    
    String number = scanner.nextLine();
    if(phone.addContact(name, number)) {
        System.out.println(name   " Added successfully");
    } else{
        System.out.println("Error: contact already present");
    }
}

the phone.addContact method:

public boolean addContact(String name, String number) {
    if (doesContactExist(name) < 0) {   
        System.out.println("Contact with name: "   name   " added successfully");
        Contact newContact = new Contact(name, number);
        this.contacts.add(newContact);
        return true;
    } 
    System.out.println("Error: contact already exists");
    return false;
}

CodePudding user response:

I tested your code and you need to remove the extra scanner.nextLine();.

import java.util.*;
public class MyClass {
    public static void main(String args[]) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter new contact name");
        String name = scanner.nextLine();
        System.out.println("Enter new contact number");
        
        String number = scanner.nextLine();
        System.out.println(name);
        // Prints out name
    }
}

I removed that extra function call and it is working correctly now.

  • Related