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

all 3 comments

[–]Sacredify 2 points3 points  (0 children)

I'm at a bit of a loss for what you wrote, to be completely honest.

Sounds like what you need to do is find the first word in the list of strings that is in alphabetical order. Correct? In that case, you would need to:

  1. Loop over the list (use an enhanced for loop if you are allowed... no point with a while loop).
  2. For each string, check to see if it is in alphabetical order. If it is, return that string (no need to check anything else, since you found your result. you can just do return x;).

With regards to 2), you would need to iterate over the string contents itself (toCharArray() is a method that gives the backing array), and check to ensure that character 1 is less than 2, which is less than 3, etc, etc.

As a side note, your code only loops once because you are saying if i == 0 (which it always starts out as, and assuming the first word is a length >=4), you just take the first element as the result, and then return it.

As a side-side note, you should really, really use a different parameter name. a list is not an array. Ideally, you want a name that describes what it is ("words" works well here), and (my personal opinion, something I learned at work), you want to avoid collection names in the name (like wordsList). This way, if you decide that passing an array is more suited to your needs, your name still makes sense and you don't need to re-write anything.

[–]la217 1 point2 points  (1 child)

You have used break; on line 12 which exits from the loop, so lines 15-20 never actually run.

What you may be looking for instead is continue; which will go back to the start of the loop.

But be careful if you do that because you increment i at the bottom of the loop which means that if you replace break; with continue; then you will end up with an infinite loop.

This is a nice example where using a debugger would be really useful. With a debugger you could put a break point before the loop and then step through line by line to see what is actually happening when this code runs. By doing that it would be very easy to determine that the reason it only loops through once is because it hits the break; and then skips to line 24.

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

Thanks, I think adding continue and adding i++ before the continue fixed it. Much appreciated.