Java:如何连续扫描输入?

时间:2015-01-29 11:24:09

标签: java oop input java.util.scanner

我正在尝试用Java编写一个允许用户修改AddressBook的程序。我编写了创建AddressBook的代码和允许修改它的函数:

public class AddressBookEntry 
{
    private String name, phone, email;
    public AddressBookEntry(String name, String phone, String email)
    {
        this.name = name;
        this.phone = phone;
        this.email = email;
    }
    public String getName() 
    {
        return name;
    }
    public String getPhone() 
    {
        return phone;
    }
    public String getEmail() 
    {
        return email;
    }
}

import java.util.ArrayList;

public class AddressBook
{
    private ArrayList<AddressBookEntry> book = new ArrayList<AddressBookEntry>();
    public AddressBook(String bookname)
    {

    }
    public void addEntry(String name, String phone, String email)
    {
        book.add(new AddressBookEntry(name, phone, email));
    }
    public AddressBookEntry Search(String searchkey)
    {
        for (AddressBookEntry entry: book)
        {
            if (entry.getName() == searchkey)
                {
                    return entry;
                }
        }
    return null;
    }
    public void removeEntry(String searchkey)
    {
        AddressBookEntry removeentry = Search(searchkey);
        book.remove(removeentry);
    }
}

我现在正在尝试编写另一个使用用户输入来执行上述功能的类。我需要不断扫描输入。

我已尝试使用Scanner,但只有在程序提示输入时才能使用此功能,例如"Type an entry to add: "。在没有程序提示输入的情况下解决此问题的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

使用此放入while您的退出条件:

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

while (...) {
    System.out.print("Type an entry to add: ");
    String input = bufferedReader.readLine();
    ...
}

现在您在input中输入了用户输入的字符串。

示例:

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

while (true) {
    System.out.print("Type an entry to add: ");
    String input = bufferedReader.readLine();
    if (input.equals("exit"))
        break;
    ...
}

当用户输入"exit"时,此程序退出。