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