I’m taking in a text file and storing each word in an arraylist. However the problem is, when I iterate through the arraylist and print the contents, the words appear many times and not necessarily in the right order. Here’s a snippet of the code below:
public static void main(String args[])
{
try
{
ArrayList storeWord = new ArrayList();
Scanner scannerWord = new Scanner(new File("word"));
while(scannerWord.hasNext()) {
String word = scannerWord.next();{
storeWord.add(word);
Iterator itr = storeWord.iterator();
while(itr.hasNext())
System.out.println(itr.next());
}
Does anyone know what the problem could be and how to fix it?
Thanks.
Try this
Your ‘print’ loop was nested in your ‘read’ loop.