Reading words until an empty line 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&lt;String&gt; words = new ArrayList&lt;String&gt;();

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;
    }
 }
}
}
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&lt;String&gt; readWords(Scanner source) {
    String word = null;
    List&lt;String&gt; words = new ArrayList&lt;&gt;();
    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&lt;String&gt; words = readWords(new Scanner(System.in));
    words.forEach(System.out::println);
}