Object-Oriented Programming with Java, part I – Exercise 60

This program asks the user for multiple words and then prints them out in alphabetical order when an empty string has been inserted.

My Code

import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class WordsInAlphabeticalOrder {

    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        // create here an ArrayList
        ArrayList<String> words = new ArrayList<String>();

        System.out.print("Type a word: ");
        String input = reader.nextLine();
        words.add(input);

        while (input.length() != 0) {
            System.out.print("Type a word: ");
            input = reader.nextLine();

            words.add(input);
        }

        Collections.sort(words);

        System.out.print("You typed the following words:");

        for (String word : words) {
            System.out.println(word);
        }
    }
}

Model Code

import java.util.ArrayList;

import java.util.Collections;

import java.util.Scanner;

 

public class WordsInAlphabeticalOrder {

 

    public static void main(String[] args) {

        Scanner reader = new Scanner(System.in);

        // create here an ArrayList

        ArrayList<String> words = new ArrayList<String>();

 

        while (true) {

            System.out.print("Type a word: ");

            String word = reader.nextLine();

            if (word.equals("")) {

                break;

            }

            words.add(word);

        }

 

        Collections.sort(words);

        

        System.out.println("You typed the following words:");

 

        for (String word : words) {

            System.out.println(word);

        }

 

    }

}

Comments

After a four month break it is quite easy to make the same mistakes I did last time.

Leave a comment