This program accepts user input and adds it to a list until the user inputs the same word twice at which point it stops.
My Code
import java.util.ArrayList;
import java.util.Scanner;
public class RecurringWord {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
// create here the ArrayList
ArrayList<String> words = new ArrayList<String>();
boolean test = true;
String input = "";
while (test){
System.out.print("Type a word: ");
input = reader.nextLine();
if (words.contains(input)) {
test = false;
}
words.add(input);
}
System.out.println("You gave the word " + input + " twice");
}
}
Model Code
import java.util.ArrayList;
import java.util.Scanner;
public class RecurringWord {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
// create here the ArrayList
ArrayList<String> words = new ArrayList<String>();
while (true) {
System.out.print("Type a word:");
String word = reader.nextLine();
if (words.contains(word)) {
System.out.println("You gave twice the word " + word);
break;
}
words.add(word);
}
}
}
Comments
I’ll count that as somewhat of an epic failure. My boolean variable could have been replaced by a simple break in the if statement and the String variable didn’t need to be there at all. 🙂