- while循环在Java中不能正常运行。

时间:2022-12-13 14:45:32

So this should continue to loop until user hits "ENTER" or the array is filled. But after entering the first element in the array it quits the loop.

因此,在用户点击“输入”或数组被填充之前,这将继续循环。但是在进入数组中的第一个元素之后,它就会退出循环。

do 
{
    System.out.print("Enter name (or <ENTER> if done): ");
    names[index] = kb.nextLine();
    if(! (names[index].equals(""))) 
    {

        System.out.print("Enter phone number: ");
        phone[index] = kb.nextLine();

        System.out.print("Enter email address: ");
        email[index] = kb.nextLine();

        index++;
        break;
    }
} while ( ! (names[index - 1].equals("")) && index < SIZE);

Corrected

纠正

do
{
        System.out.print("Enter name (or <ENTER> if done): ");
        names[index] = kb.nextLine();

        if(! (names[index].equals("")))
            {

            System.out.print("Enter phone number: ");
            phone[index] = kb.nextLine();

            System.out.print("Enter email address: ");
            email[index] = kb.nextLine();

            }   
        index++;

    } while ( ! (names[index - 1].equals("")) && index < SIZE);

2 个解决方案

#1


5  

This is very simple. break; exits the loop. Remove it.

这是非常简单的。打破;退出循环。删除它。

EDIT: Also, in your condition of the loop you use [index - 1]. Now, if your input is empty (user pressed Enter) the index won't be incremented and it will point to the previous item. Change it to just [index] and it'll work.

编辑:同样,在你的循环条件下你使用[索引- 1]。现在,如果您的输入是空的(用户按下Enter),索引将不会增加,它将指向上一个项目。把它改为[索引],它就会起作用。

#2


0  

The problem is the break and if-statement. Working example:

问题在于break和if-statement。工作的例子:

do {
    System.out.print("Enter name (or <ENTER> if done): ");
    names[index] = kb.nextLine();

    if (names[index].equals(""))
        break;

    System.out.print("Enter phone number: ");
    phone[index] = kb.nextLine();

    System.out.print("Enter email address: ");
    email[index] = kb.nextLine();

    index++;

} while (index < SIZE);

#1


5  

This is very simple. break; exits the loop. Remove it.

这是非常简单的。打破;退出循环。删除它。

EDIT: Also, in your condition of the loop you use [index - 1]. Now, if your input is empty (user pressed Enter) the index won't be incremented and it will point to the previous item. Change it to just [index] and it'll work.

编辑:同样,在你的循环条件下你使用[索引- 1]。现在,如果您的输入是空的(用户按下Enter),索引将不会增加,它将指向上一个项目。把它改为[索引],它就会起作用。

#2


0  

The problem is the break and if-statement. Working example:

问题在于break和if-statement。工作的例子:

do {
    System.out.print("Enter name (or <ENTER> if done): ");
    names[index] = kb.nextLine();

    if (names[index].equals(""))
        break;

    System.out.print("Enter phone number: ");
    phone[index] = kb.nextLine();

    System.out.print("Enter email address: ");
    email[index] = kb.nextLine();

    index++;

} while (index < SIZE);