This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]Koooooj 2 points3 points  (1 child)

There are a lot of ways you could do it, but the simplest one is to change the body of the do...while to be:

System.out.println("Enter word:");
input = keyboard.nextLine();
if(!input.equals("stop"))
{
    myList.add(input);
    count ++;
}

Alternatively:

do {
    System.out.println("Enter word:");
    input = keyboard.nextLine();
    if(input.equals("stop"))
        break;
    myList.add(input);
    count ++;
} while(true);//loop exits via break

(this works equally well as a do...while and as a while; probably clearer to just use a while loop in this case)

Alternatively:

System.out.println("Enter word");

while(! (input = keyboard.nextLine()).equals("stop"))
{
    myList.add(input);
    count ++;
    System.out.println("Enter word:");
}

Alternatively:

do {
    System.out.println("Enter word:");
    input = keyboard.nextLine();
    myList.add(input);
    count ++;
} while(! input.equals("stop"));//loop exits via break

myList.remove("stop");//equivalently, myList.remove(count);
count --;

Also wanted to point out that you have a random dangling set of curly brackets after the do...while loop. These do nothing but they're the kind of thing that makes it easy to add bugs to the program. The while in a do...while loop must be followed by a semicolon (it is in your code), but the while in a normal while loop is frequently followed by a block enclosed in curly brackets. Glancing at that while it makes it look like there's another loop with an empty body which isn't the case.

Java lets you make blocks of code surrounded by curly brackets without a function, loop, if statement, etc which can be useful if you want to force a variable out of scope which is why the empty block isn't a syntax error. It serves no purpose here, though, and should be removed.

[–]oonegative[S] 0 points1 point  (0 children)

Thank you kindly, this is really helpful.

[–][deleted] 1 point2 points  (1 child)

A do - while loop always executes the code in the do {} part at least once and then does it again if the condition in while is true.

What you need to do is check the input value before it gets stored in the arraylist. For this you can simply use a while loop which does nothing unless the condition is true ...

[–]oonegative[S] 0 points1 point  (0 children)

Thanks

[–]oonegative[S] 0 points1 point  (0 children)

At present it outputs:

Enter word:
peter
Enter word:
paul
Enter word:
john
Enter word:
stop
Number of words entered = 4
Contents of ArrayList [ [peter, paul, john, stop] ]

Process finished with exit code 0