3

I want to create an Arraylist that holds strings as the user inputs them:

System.out.println("How many words do you want to enter?");
int numVerbs = scan.nextInt();
ArrayList <String> verbs = new ArrayList <String> (numVerbs);
System.out.println("Start entering words:");
for(int i=0;i<=numVerbs;i++){
   verbs.add(scan.nextLine());
}
System.out.print(verbs.size());
}

The problem is that when I create and add the strings to the list, and then print out the size of the arraylist, it's one element larger than I want it to be.

For example, I'll enter 3 as how many words I want to add, then I'll input 3 words. However, when I print back the size of the arraylist it's 4 - not 3.

Maybe it has something to do with the verbs.add to an empty list? Idk, I'm at a loss.

MajorMoo
  • 33
  • 2
  • i <=, array list gets recreated with more capacity, change <= to – whatamidoingwithmylife Dec 30 '17 at 19:38
  • I suggest you learn how to use a debugger. This is an invaluable tool for anyone learning to write computer programs. – Code-Apprentice Dec 30 '17 at 19:38
  • Possible duplicate of [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – Turing85 Dec 30 '17 at 19:39
  • @GCP your explanation is kind of missleading. While the `<=` in this particular case is the cause of the resize, `ArrayList`s do in general always resize when they reached their capacity (I am quite sure that you are well aware of this, just wanted to clarify for future readers). – Turing85 Dec 30 '17 at 19:45
  • @Turing85 I just put it out there because he is explicitly assigning capacity to the ArrayList. – whatamidoingwithmylife Dec 30 '17 at 19:48

2 Answers2

1

start the loop at 1:

for(int i = 1; i <= numVerbs; i++){ ... }

or change the condition from i <= numVerbs to i < numVerbs

for(int i = 0; i < numVerbs; i++){ ... }

This is necessary because as is, the for loop is starting at 0 and then looping until the number entered inclusive hence you're performing one extra iteration than required.

Ousmane D.
  • 50,173
  • 8
  • 66
  • 103
  • Thanks for the reply! That fixed the size of the arraylist, but now I can only input 2 words when it outputs a size of 3. Is there a way to input 3 words into the array list and have it also output the size as 3? – MajorMoo Dec 30 '17 at 20:13
  • @MajorMoo insert a `scan.nextLine();` call before the for loop to consume the last newline character of your input. see [here](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo) for more explanation as to why it's required. – Ousmane D. Dec 30 '17 at 20:18
  • Ooooohhh - yeah that fixed it, thanks! – MajorMoo Dec 30 '17 at 20:21
0

You can replace for:each loop with while scan.hasNextLine() as well, provided you don't need to ask user the number of words upfront.

Jarek Soja
  • 31
  • 6