How to print second word alphabetically ? | JAVA

382 views Asked by At

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."

1

There are 1 answers

10
hfontanez On

Use Scanner#nextLine() to capture many space-delimited characters and then split the input into an array of words using String#split(String) method.

Scanner scanner = new Scanner(System.in);
System.out.println("Enter a sentence:");
String sentence = scanner.nextLine();
String[] words = sentence.split("\\s");

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.

words = Stream.of(words).sorted().toArray(String[]::new);

However, for this specific assignment, the OP stated that a while loop must be used exclusively. Therefore, using only while loop:

int i = 0;
while (i < words.length - 1) {

    // Checking the condition for two
    // adjacent words of the array
    if (words[i].compareTo(words[i + 1]) > 0) {

        // Swapping the elements if the next word
        // precedes the current alphabetically
        String temp = words[i];
        words[i] = words[i + 1];
        words[i + 1] = temp;

        // we must keep resetting the index back to zero
        // when a sort occurs
        i = -1;
    }
    i++;
}

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):

the quick brown fox jumps over the lazy dog

Sorted alphabetically should result in

[ brown, dog, fox, jumps, lazy, over, quick, the, the ]

Going over the first few iterations:

  1. In the first iteration, the words "the" and "quick" get swapped and the index i is reset back to zero.
  2. In the second iteration, (i equals zero again), the words "quick" and "the" are in correct order with respect to each other. They are not swapped and the index is incremented by one.
  3. In the third iteration (i equals to 1), the words "the" and "brown" are swapped and the index is reset back to zero.
  4. In the fourth iteration, (i equals zero again), the words "quick" and "brown" are sorted and the index is reset back to zero.

After 4 iterations, the array is partially sorted:

[ brown, quick, the, fox, jumps, over, the, lazy, dog ]

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:

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter a sentence:");
    String sentence = scanner.nextLine();
    String[] words = sentence.toLowerCase().split("\\s");
    if (words.length < 2) {
        System.err.println("Not enough words were entered");
        System.exit(-1);
    }

    int i = 0;
    while (i < words.length - 1) {
        if (words[i].compareTo(words[i + 1]) > 0) {
            String temp = words[i];
            words[i] = words[i + 1];
            words[i + 1] = temp;
            i = -1;
        }
        i++;
    }

    System.out.println("The second word is: " + words[1]);
}

For the sentence I used in this example, the output prints out

dog

Based on this new information:

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.

The solution will prompt the user in a loop (using while loop as a given constraint).

String input = "";
Scanner scanner = new Scanner(System.in);
List<String> words = new ArrayList<>();
boolean isExit = false;
System.out.println("For this problem, you must enter at least two words.");
while (!isExit) {
    System.out.print("Enter a word (type \"exit\" to finish): ");
    input = scanner.next();
    isExit = "exit".equalsIgnoreCase(input);
    if (!isExit) {
        words.add(input.toLowerCase());
    }
}
scanner.close();

The code snippet above does a couple, necessary, things:

  1. Uses ArrayList rather than an array to allow unbounded growth of the collection. "Resizing" an array is a much costlier process than using this Java specialized class.
  2. Checks if the word entered is "exit" which is the special-case input to terminate the loop. It is not, and should not, part of the words to be evaluated.

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()

if (words.size() < 2) {
    System.err.println("Not enough words were entered");
    System.exit(-1);
}
Collections.sort(words);
System.out.println("Second word in alphabetical order: " + words.get(1));

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 using Streams API:

List<String> sortedWords = words.stream().sorted().collect(Collectors.toList());
System.out.println("Second word in alphabetical order: " + sortedWords.get(1));

Using the same words I used in my previous version, the result is the same (as expected)

Enter a word (type "exit" to finish): the
Enter a word (type "exit" to finish): quick
Enter a word (type "exit" to finish): brown
Enter a word (type "exit" to finish): fox
Enter a word (type "exit" to finish): jumps
Enter a word (type "exit" to finish): over
Enter a word (type "exit" to finish): the
Enter a word (type "exit" to finish): lazy
Enter a word (type "exit" to finish): dog
Enter a word (type "exit" to finish): exit
Second word in alphabetical order: dog