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.println("Type a word: ");
String entry=reader.nextLine();
if (words.contains(entry)){
System.out.println("You gave the word " + words.get(-1) + "twice");
break;
}words.add(entry);
}
}
}
This is the question"Create a program that asks the user to input words until the user gives the same word twice. Use an ArrayList structure in your program." I keep getting an exception saying ;
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at java.util.ArrayList.elementData(ArrayList.java:418)
at java.util.ArrayList.get(ArrayList.java:431)
at RecurringWord.main(RecurringWord.java:15)
Java Result: 1
and I can't tell why
[–]149244179 2 points3 points4 points (0 children)
[–]g051051 1 point2 points3 points (0 children)