user2993639
user2993639

Reputation: 21

Do-While loop not operating properly in Java

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);

Upvotes: 2

Views: 78

Answers (2)

PurkkaKoodari
PurkkaKoodari

Reputation: 6809

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.

Upvotes: 5

knordbo
knordbo

Reputation: 552

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);

Upvotes: 0

Related Questions