I must ask for inputs from the user (there is not any limit for the input word count) and then the program must print the second word that comes in alphabetical order.
Instructions
Write a program, that inputs words from the user, until the user enters ‘exit’. When the user enters ‘exit’ the program should display the word that comes second alphabetically. Your program should not be case sensitive.
"you should only use while loops in your solutions."
Use
Scanner#nextLine()to capture many space-delimited characters and then split the input into an array of words usingString#split(String)method.Since the words need to be sorted (the question asks for "the second word that comes in alphabetical order", we can use various methods. An easy way to do this is by using the Java Streams API.
However, for this specific assignment, the OP stated that a
whileloop must be used exclusively. Therefore, using onlywhileloop:This is obviously not the most optimized loop, but for academic purposes is clear enough to understand. Using the following sentence as an example (using all lowercase letters for simplicity):
Sorted alphabetically should result in
Going over the first few iterations:
After 4 iterations, the array is partially sorted:
The process continues until all the words that precede their previous neighbor "bubble up" to the surface. Eventually, all the words will be sorted, the index will be equal to the word count, and the process will stop. For the sentence I provided, it takes 90 iterations for the sorting to complete. This value is not relative to the size of the array. The number of iteration depend on other factors as well
Putting it all together, the solution looks like this:
For the sentence I used in this example, the output prints out
Based on this new information:
The solution will prompt the user in a loop (using
whileloop as a given constraint).The code snippet above does a couple, necessary, things:
ArrayListrather than an array to allow unbounded growth of the collection. "Resizing" an array is a much costlier process than using this Java specialized class.Once the loop operation concludes, the rest of the code should be pretty much the same. We must evaluate the collection of words and check which is the second word in alphabetical order. For this, all we need to do is sort the collection and return whichever word is at index 1. Since I already provided a looping solution to sort the array, I will show better ways to sort a collection. Of course, the easiest way is calling
Collections#sort()The caveat with
Collections#sort()is that the operation modifies the given list. This may or may not be desirable. There might be cases when the original list must be preserved. For those cases, we can use another Java standard library approach usingStreamsAPI:Using the same words I used in my previous version, the result is the same (as expected)