Reputation: 374
The problem I am having is that when there is an even amount of input before the sentinel is typed, it only outputs the even strings (ex: yes, no, -1 will print no) and when there is an odd amount of input, the program keeps running even though the sentinel was used.
//takes words (strings) from the user at the command line
//returns the words as an ArrayList of strings.
//Use a sentinel to allow user to tell the method when they are done entering words.
public static ArrayList<String> arrayListFiller(){
ArrayList<String> stringArrayList = new ArrayList();
System.out.println("Enter the Strings you would like to add to the Array List.");
System.out.println("Type -1 when finished.");
Scanner in = new Scanner(System.in);
while(!in.nextLine().equals("-1")){
String tempString = in.nextLine();
stringArrayList.add(tempString);
}
return stringArrayList;
}
public static void printArrayListFiller(ArrayList<String> stringArrayList){
for(int i = 0; i < stringArrayList.size(); i++){
String value = stringArrayList.get(i);
System.out.println(value);
}
}
Upvotes: 1
Views: 49
Reputation: 9261
The problem that I think you are having is that you're calling nextLine too many times. If you take a look at these lines of code,
while(!in.nextLine().equals("-1")){
String tempString = in.nextLine();
stringArrayList.add(tempString);
}
Say I want to enter "Bob" and then -1 to exit. What you're doing is reading in"Bob" to test that it is not the sentinel but then you're reading in the sentinel and adding it to the collection.(wo even testing that it is the sentinel value)
My fix is to just call the nextLine method once and test it as you get it and then process it. To do this, you have to have a local variable outside the while loop and assign it to nextLine(), that is
String temp
while(!(temp=in.nextLine()).equals("-1")) {
.add(temp)
}
This way, you can test the line you're reading in is not the sentinel value and you have a way of adding it to the collection. Hope that helps
Upvotes: 1