0

I wrote a program that has an arraylist of users so it should either create a new user and store the user's name in an arraylist or choose an existing user from an arraylist. The problem is, when I run the code I can choose an option but when I want to create a new user I cannot type anything. Why does that happen and how can I fix this?

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;

public class Main {

private ArrayList<String> users;

public static void main(String[] args) {
    Main m = new Main();
    m.menu();
}

public void createNewUser(String name) {
    users.add(name);
}

public boolean search(String username) {
    if (users.contains(username))
        return true;
    else
        return false;
}

public void displayUsers() {
    Iterator<String> itr = users.iterator();
    while (itr.hasNext()) {
        String name = itr.next();
        System.out.println(name);
    }
}

public void menu() {
    users = new ArrayList<String>();
    int choice = 0;
    String name;
    Scanner input = new Scanner(System.in);

    System.out.println("Choose an option:");
    System.out.println("1- Create new user");
    System.out.println("2- Select current user");

    choice = input.nextInt();

    if (choice == 1) {
        System.out.println("Enter your name: ");
        name = input.nextLine();
        createNewUser(name);
        displayUsers();
    } else {
        do {
            displayUsers();
            System.out.println("Enter your username: ");
            name = input.nextLine();
            if (search(name)) {
                System.out.println("User found");
                break;
            }
            else
                System.out.println("This username does not exist.");
        } while (!search(name));

    }

}
}
  • 1
    Well known behavior you must consume the newline [Check this answer](http://stackoverflow.com/questions/13102045/skipping-nextline-after-use-nextint) – gtgaxiola Oct 01 '14 at 18:14
  • 1
    Why use `if`-`else` in the `search()` method; you can just have `return users.contains(username)`, which eliminates the need for a separate method from `contains()` in the first place... – bcsb1001 Oct 01 '14 at 18:17

1 Answers1

0
System.out.println("Choose an option:");
    System.out.println("1- Create new user");
    System.out.println("2- Select current user");

    choice = input.nextInt();
    input.nextLine();

Try adding input.nextLine(); after your choice.

brso05
  • 12,634
  • 1
  • 17
  • 37