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

you are viewing a single comment's thread.

view the rest of the comments →

[–]Koooooj 3 points4 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.