1

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);
    }
}

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

haha can you hit me up with an upvote too? Appreciate the love. I need some points to get me out of the question ban
I will upvote your solution as soon as I can. I am fairly new to this site, so I am not permitted to upvote until I get to a reputation of 15. Thank you again for the help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.