0

I am trying to create a program, that takes asks the user to enter a Contact name, and a contact number, and then stores that contact in my ArrayList entries. Once the user has entered the first contact, they are given the choice to add another contact to the array list, or to not add any more contacts, exiting the loop, and simple displaying all of the contacts stored in entries.

I am currently having trouble exiting my while loop, the first contact adds correctly to the array list, and then displays the "Add Another?" message, however from there it falls apart, if i type Y, the console simply just hangs with the cursor flashing, instead of asking for the next contacts name and number, and if i type N, it once again just hangs and does nothing, instead of exiting the loop and displaying the contents of my ArrayList like intended.

Any help towards solving this issue would be much appreciated! I have a feeling it may be something to do with my loop, but can't for the life of me see what!

Thanks in advance!

while (addMore != false)
    {
        System.out.print("Contact name: ");
        String name = sc.nextLine();
        System.out.print("Contact Number: ");
        String TelNo = sc.nextLine();

        // add the user inputted contact to ArrayList entries.
        entries.add(new TelEntry(name, TelNo));


        System.out.print("Add Another?(Y/N): ");
        if(sc.nextLine() == "N")
        {
            addMore = false;
            break;
        }

        else if(sc.nextLine() !="Y" && sc.nextLine() !="N")
        {
            System.out.println("Please Select Y or N");
        }

        addMore = true;

    }

    // FOR LOOP TO PRINT ALL ENTRIES IN ARRAY
    for(int i=0; i<entries.size(); i++)
    {
        System.out.println(entries.get(i));
    }
freshwaterjoe
  • 101
  • 3
  • 16
  • 4
    Don't compare Strings with `==`, use `equals` – Jaqen H'ghar Aug 23 '14 at 15:02
  • Each time you call `nextLine()` you are reading next line so using it in condition is not best thing to do. Consider storing result from this method so you could use it in few conditions. Also don't compare strings with `==` since String are objects so you would compare identity of objects, not their state. To compare state use `equals`. BTW `while (addMore != false)` is the same as `while (addMore == true)` which is same as `while (addMore)` – Pshemo Aug 23 '14 at 15:04

0 Answers0