如果某個字母存在于另一個 ArrayList 中,我正在嘗試更新包含字母的字符串 ArrayList。但是,代碼只更新它遇到的第一個實例,而不是所有實例。ArrayList word 包含字母 h,e,l,l,o, ,w,o,r,l,d,ArrayList underscores 包含與單詞中每個字母對應(yīng)的下劃線。對于單詞中的每個字母,我想獲取它的索引并在同一索引處用該字母更新下劃線。例如,對于 l,我想更新下劃線以顯示除了在 word 中找到字母 l 的索引之外的下劃線。import java.util.ArrayList;class Main { public static void main(String[] args) { ArrayList<String> word = new ArrayList<String>(); word.add("h"); word.add("e"); word.add("l"); word.add("l"); word.add("o"); word.add(" "); word.add("w"); word.add("o"); word.add("r"); word.add("l"); word.add("d"); for (String letter:word) { System.out.print(letter); } System.out.println(); ArrayList<String> underscores = new ArrayList<String>(); for (String letter:word) { if (letter.equals(" ")) { underscores.add(" "); } else { underscores.add("-"); } } for (String letter: underscores) { System.out.print(letter); } String l = "l"; for (String s:word) { if (s.equals(l)) { int index = word.indexOf(s); underscores.set(index, l); } } System.out.println(); for (String s:underscores) { System.out.print(s); } }}
1 回答

白豬掌柜的
TA貢獻(xiàn)1893條經(jīng)驗 獲得超10個贊
問題是word.indexOf(s)
總是返回給定元素第一次出現(xiàn)的索引。來自List
文檔:
返回此列表中指定元素第一次出現(xiàn)的索引,如果此列表不包含該元素,則返回 -1。更正式地說,返回最低索引 i 使得 (o==null ? get(i)==null : o.equals(get(i))),如果沒有這樣的索引則返回 -1。
for-each
您可以使用簡單的舊for
循環(huán)來更新列表中給定位置的字符串,而不是使用循環(huán)underscores
:
?for (int i = 0; i < underscores.size(); i++) {
? ? if (word.get(i).equals(l)) {
? ? ? ? underscores.set(i, l);
? ? }
}
輸出將是:
hello world
----- -----
--ll- ---l-
添加回答
舉報
0/150
提交
取消