读取字符串并将其添加到ArrayList

时间:2014-10-01 18:12:43

标签: java string arraylist

我编写了一个程序,其中包含用户的arraylist,因此它应该创建一个新用户并将用户的名称存储在arraylist中,或者从arraylist中选择现有用户。问题是,当我运行代码时,我可以选择一个选项,但是当我想创建一个新用户时,我无法输入任何内容。为什么会发生这种情况?我该如何解决这个问题?

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 个答案:

答案 0 :(得分: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();

尝试添加input.nextLine();在你选择之后。