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

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

My Code

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

public class WordsInReverseOrder {

    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.reverse(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 WordsInReverseOrder {

    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.reverse(words);

        

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

 

        for (String word : words) {

            System.out.println(word);

        }

    }

}

Comments

I am obviously out of practice. Although my code works fine the model code uses the condition true for the while loop and then an if statement to break the loop where mine repeats code to make sure that the string contains something before the condition is applied.

Leave a comment