我在循環中比較兩個字符串時遇到了問題。比較ArrayList中的兩個字符串
說我想把兩個單詞放在ArrayList中。我決定通過inputDialogeBox寫兩個單詞並將它們放入列表中。如果兩個單詞相同,則第二個單詞不會被添加到列表中。
但是,當我比較兩個字符串程序似乎不關心,如果他們是相同的,並且都在列表中結束。
繼承人我的代碼:
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());
}
}
而我的等級:
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;
}
}
我的猜測是,這個問題是我周圍添加一個默認值,只是爲了找點與循環。否則,如果ArrayList爲空,我不能啓動我的循環。但也許有更好的方法?
感謝
如果列表中有*任何*字不是單詞,您正在將該單詞添加到列表中。 – Andreas
對不起。我是一個初學者:-)
1)如果ArrayList爲空 - 將第一個值添加到列表 2)我遍歷該唯一值。 3)如果字符串(默認)與第一個字不同,它將第一個字添加到ArrayList 4)如果字符串(默認和word1)不是第二個字,它將它添加到ArrayList 但我想我搞砸了:-) – acroscene
如果你想防止重複,使用一套,而不是一個列表。 –