This program accepts input from a user until an empty string is input and then it prints all the previous words.
My Code
import java.util.ArrayList;
import java.util.Scanner;
public class Words {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
ArrayList<String> words = new ArrayList<String>();
System.out.print("Type a word: ");
String input = reader.nextLine();
while (!input.isEmpty()) {
words.add(input);
System.out.print("Type a word: ");
input = reader.nextLine();
}
for (String word : words) {
System.out.println(word);
}
}
}
Model Code
import java.util.ArrayList;
import java.util.Scanner;
public class Words {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
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);
}
System.out.println("You typed the following words:");
for (String word : words) {
System.out.println(word);
}
}
}
Comments
They are pretty close but since mine has repetition of the questions (inside and outside the loop) I would have to say the model code is better. It doesn’t actually follow the instructions given though. eg; the hint to use input.isEmpty()…..