2

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 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

+1 break does not exit from an if statement. It will exit from the nearest loop. While you're at it, here is some literature about a break bug: users.csc.calpoly.edu/~jdalbey/SWE/Papers/att_collapse.html
When I remove the break, now the loop won't exit when I hit enter
Got it. Moved the index++ outside the if statement, so that it is now incremented if I hit enter.
@user2993639 Yes, that is another way to do it.
0

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

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 Comment

Removed the break, but now the loop won't exit when I hit enter

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.