When printing out the user input as indvidual words within a line I get a printout of all the words in that line.
System.out.println(userInput.next());
However, when I add the indvidual words to an ArrayList I appear to be getting random words back:
al.add(userInput.next());
Could someone explain to me what’s going on?
Thanks.
This is a full copy of the code:
import java.util.*;
public class Kwic {
public static void main(String args[]){
Scanner userInput = new Scanner(System.in);
ArrayList<String> al = new ArrayList<String>();
while(userInput.hasNext()){
al.add(userInput.next());
System.out.println(userInput.next());
}
}
}
Because
next()consumes the next token from the scanner. Thus, when you have:You are actually consuming two tokens from the scanner. The first is being added to the
ArrayListand the other is being printed toSystem.out. A possible solution is to store the token in a local variable, and then add it to the array and print it: