-1

我想创建一个构造函数,我将要求用户输入将存储在 ArrayList 中的人名,然后要求用户输入该人的电话号码,该电话号码也将存储在另一个 ArrayList 中。这应该保持循环,除非用户输入“否”,然后结束循环。

但是,当我在演示类中运行该方法时,第一次迭代工作正常,但第二次超时,它不起作用,因为它跳过了用户输入的人名并直接跳转到电话号码的输入。

我到底做错了什么?

public PhoneBookEntry()
{
    System.out.println("Enter the following requested data.");
    System.out.println("");
    int i=0;
    while(i==0)
    {       
        System.out.println("Enter the name of the person (enter 'no' to end): ");
        input_name = kb.nextLine();
        if(!input_name.equalsIgnoreCase("no"))
        {
            name.add(input_name);
            System.out.println("Enter the phone number of that person (enter '-1' to end): ");
            input_number = kb.nextLong();
            phone_number.add(input_number);
        }
        else
        {
            name.trimToSize();
            break;
        }

        System.out.println("");
    }
}
4

1 回答 1

3

您的问题在于您的 Scanner 对象。了解 ScannernextLong()和类似方法(例如nextInt()nextDouble()next())不处理行尾 (EOL) 令牌。你必须自己费力去处理。

一种方法是添加这样的调用nextLine()

    System.out.println("Enter the name of the person (enter 'no' to end): ");
    input_name = kb.nextLine();
    if(!input_name.equalsIgnoreCase("no"))
    {
        name.add(input_name);
        System.out.println("Enter the phone number of that person (enter '-1' to end): ");
        input_number = kb.nextLong();
        phone_number.add(input_number);

对此:

    System.out.println("Enter the name of the person (enter 'no' to end): ");
    input_name = kb.nextLine();
    if(!input_name.equalsIgnoreCase("no"))
    {
        name.add(input_name);
        System.out.println("Enter the phone number of that person (enter '-1' to end): ");
        input_number = kb.nextLong();
        kb.nextLine();  // **** added to handle the EOL ****
        phone_number.add(input_number);

结束是的,评论是正确的——这是一个糟糕的构造函数。构造函数不是用于直接与用户交互,而是仅用于创建对象。

于 2013-03-09T03:59:06.763 回答