0
Why when I use an ArrayList, the String I try to add, it repeats 3 times on the same Index?
I try to add words to an ArrayList of Strings but whenever I write the word it adds itself 3 times. Can somebody help me? fragment of code: myArray.add(JOptionPane.showInputDialog("Type a word"));
6 Respostas
+ 2
When I choose option 1 and enter a word, it is only added to the List p 1 time. I checked this by adding:
System.out.println(p.size());
for(String s: p) {
System.out.println(s);
}
to the bottom of the do while loop after the switch statement. It will output a size of 2 and then the "" that was added to the List before the loop (p.add("");), plus the word that I added. With the p.add(""); line commented out it just adds the words that I add to the list and doesn't repeat them. So your issue lies somewhere in your output if it is elsewhere.
I changed:
//AbrahamRandom randomGenerator = new Random();
//int randomInt = randomGenerator.nextInt(5);
to:
int randomInt = new Random().nextInt(5);
so that the code would run on my computer.
When I go through the dialog and add all 5 words (first, second, third, fourth, fifth) the output from the code I added is also as expected:
1
first
2
first
second
3
first
second
third
4
first
second
third
fourth
5
first
second
third
fourth
fifth
You do however need to change your case 2: remember that a List or ArrayList is also zero based like an array and b = p.get(5); will go beyond the end of the ArrayList and result in an error. You also don't really need a switch for case 2 as you could just use the random number returned within your p.get(c);
c = new Random().nextInt(5);
System.out.print(p.get(c));
+ 3
Your code fragment is too small. Most likely the issue lies elsewhere.
+ 2
BTW you can use this line of code to also handle if someone clicks the cancel button so that it will exit gracefully per your switch case 3 instead of throwing an error and crashing.
a = (b = JOptionPane.showInputDialog("¿Qué desea hacer?\n\n1.Ingresar Palabras(5 Palabras)\n2.Iniciar Juego\n3.Salir")) != null ? Integer.parseInt(b) : 3;
Where the variable b refers to String b;
This still won't handle if someone enters something other than an integer however.
+ 1
Let me write all my code, so u can see
+ 1
Thank you very much :)
0
Here it is. It isnt finish, im still working on it, but basically Im trying to get 5 words given by the user and later on choose one randomly but, when it chooses the word, it repeats 3 times
https://code.sololearn.com/comTRGkDgxbl/?ref=app