HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Reading words until an empty line

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
readinglineuntilwordsempty

Problem

This following code executes correctly.I was wondering if there are better ways to write this code instead of using while(true) and break.For example using expressions,flags, do-while,etc.

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

public class Words {
public static void main(String[] args) {
    Scanner reader = new Scanner(System.in);
    ArrayList words = new ArrayList();

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

if(word.isEmpty()){
    System.out.println("You typed the following words:");
    for(String result: words){
    System.out.println(result);
    }
    break;
    }
 }
}
}

Solution

There are a few things in here that make sense. The first one is to use a function, and to return a List of words from that. The next thing is to use a do-while loop instead of a while loop... actually, truth is that I would personally use an assignment in the while condition. This is relatively uncommon, so let me explain:

private static List readWords(Scanner source) {
    String word = null;
    List words = new ArrayList<>();
    while (!(word = source.nextLine()).isEmpty()) {
        words.add(word);
    }
    return words;
}


That's a relatively complicated loop. It puts both the readline, and the loop-check in the same place. It reads the line in to word, then also makes sure that is not empty.

While the above is relatively uncommon to see, it makes the conditional really concise, and reduces duplicate checks.

Oh, and using a forEach on the resulting list makes the print really easy....

public static void main(String[] args) {
    List words = readWords(new Scanner(System.in));
    words.forEach(System.out::println);
}

Code Snippets

private static List<String> readWords(Scanner source) {
    String word = null;
    List<String> words = new ArrayList<>();
    while (!(word = source.nextLine()).isEmpty()) {
        words.add(word);
    }
    return words;
}
public static void main(String[] args) {
    List<String> words = readWords(new Scanner(System.in));
    words.forEach(System.out::println);
}

Context

StackExchange Code Review Q#105141, answer score: 4

Revisions (0)

No revisions yet.