Reputation: 1067
I got problems with comparing two strings in my loop.
Say I want to put two words in an ArrayList. I decide write both words through inputDialogeBox and put them in the list. If the two words are the same the second word will not be added to the list.
But when I compare the two strings the program doesnt seem to care if they are identical and both are ending up in the list.
Heres my code:
package testing;
import javax.swing.*;
public class Testing {
public static void main(String[] args) {
Word c = new Word();
// word 1
String word;
word = JOptionPane.showInputDialog("Write a word: ");
System.out.println("word1 = " + word);
c.setWord(word);
// word 2
word = JOptionPane.showInputDialog("Write a new word: ");
System.out.println("word2 = " + word);
c.setWord(word); // sätt kortet≤
System.out.println("words = " + c.getWord().size() + " " + c.getWord());
}
}
And my class:
package testing;
import java.util.ArrayList;
public class Word {
ArrayList<String> words = new ArrayList<>();
public void setWord(String word) {
// set first value in arraylist to start the loop
if (words.isEmpty()) {
words.add("default");
}
for (int i = 0; i < words.size(); i++) {
if (!words.get(i).equals(word)) {
words.add(word);
System.out.println("words.get(i): " + words.get(i) + " word: " + word);
break;
}
}
}
public ArrayList getWord() {
return words;
}
}
My guess is that the problem is around I add one defaultvalue, just to get something to loop with. Otherwise if the ArrayList is empty I cannot start my loop. But maybe there is a better way?
Thanks
Upvotes: 2
Views: 1905
Reputation: 1172
The issue is that you are not checking for all of the values, only one by one. For the first word, you check against 'default' and add to the list. For the second word, you check against 'default' first, and since this is not equal, you add that word to the list also.
public void setWord(String word) {
boolean exists = false;
for (int i = 0; i < words.size(); i++) {
if (words.get(i).equals(word)) {
exists = true;
break;
}
}
if (!exists) {
words.add(word);
System.out.println("words.get(i): " + words.get(i) + " word: " + word);
}
}
or you could use ArrayList contains:
public void setWord(String word) {
if(!words.contains(word)) {
words.add(word);
System.out.println("words.get(i): " + words.get(i) + " word: " + word);
}
}
Upvotes: 1
Reputation: 21
In these type of cases you should use Set instead of ArrayList. Still below code modification should help you.
public void setWord(String word) {'
boolean found = false;
for (int i = 0; i < words.size(); i++) {
if (words.get(i).equals(word)) {
found=true;
break;
}
}
if(!found){
words.add(word);
}
}
Upvotes: 1