2017-07-19 61 views
2

如何在忽略大小寫的情況下在同一個String中檢查Array列表? 對不起,我是StackOverflow的新手。Java ArrayList在while循環中檢查相同的輸入

新編輯: 這是我在學校NetBeans迄今爲止所做的。謝謝你們! 所以我的老師想要的是以下幾點: /* 詢問名字和輸入的名字必須排序沒有doublets。 表示如果輸入兩次相同的名稱,則第二個不會出現 並添加到arrayList。第一個字母的上限應該在 的下方。 附加:即使輸入拼寫不同。 例如:Mike - > mike - > Megan - > Lucy - > STOP sout:Lucy,Megan,Mike。 Addition_2:只有多個輸入的名稱。 */

ArrayList<String> listednames = new ArrayList<>(); 

while (true) { 
    String entry = JOptionPane.showInputDialog("name:"); 
    if (entry == null) { 
     break; 
    } 
    entry = entry.trim(); 
     String firstLetter = entry.substring(0,1).toUpperCase(); 
     String end = entry.substring(1).toLowerCase(); 
     String whole = firstLetter + end; 

    if (entry.equalsIgnoreCase("stop")) { 
     break; 
    } 
    if (entry.isEmpty()) { 
     continue; 
    } 
    if (listednames.contains(entry)) { // .equalsIgnoreCase wont work with lists 
     continue; 
    } 

    listednames.add(entry); 
    Collections.sort(listednames); 
    String namen = listednames.toString(); 
    namen = namen.substring(1, namen.length()-1); 
    System.out.println(namen); 

} 
+0

你說的情況下忽略意思?如果你的意思是比較2個字符串,無論每個字符是大寫還是小寫,那麼你只需要將兩個字符串都設置爲全部較低(或較高)的大小寫字符,然後進行比較。 – ajc2000

+0

你想完成什麼?你想只存儲唯一的元素(即使我們忽略大小寫)嗎?元素的順序是重要的(如果我們添加「ab」和「cd」,應該像這樣命令或命令「cd」,「ab」也可以)? – Pshemo

+0

對不起,我的錯我沒有解釋這是什麼。我是一名學生,我們學習使用Java編寫NetBeans。我編輯的問題,並解釋什麼是想要的。謝謝大家這麼多的快捷的答案。我很感激。 – Cesc

回答

4

你有severals選擇:

如果不能在年底沒關係,你可以隨時添加的元素在lowerCaser

listednames.add(entry.toLowercase()); 

等做entry = entry.trim().toLowercase()像這樣你的包含支票將起作用

2. 檢查用的方法手動:

for (String name : listednames) { 
    if (name.equalIgnoreCase(entry)) { 
     continue; 
    } 
} 

或者使用Java八大特點:

if(listednames.stream().anyMatch(entry::equalsIgnoreCase)){ 
     continue; 
} 
+3

使用'anyMatch',而不是'filter' –

+1

您也可以使用'進入:: equalsIgnoreCase'與'anyMatch' –

2

你必須手動通過ArrayList循環和比較項目一個接一個。

for (String s : listednames) { 
    if (s.equalIgnoreCase(entry)) { 
     continue; 
    } 
} 
0

如果你想要做一個線性的時間是非常簡單的。你應該在支票使用toUpperCase()(或toLowerCase())和add方法,你可以用這個修改後的代碼嘗試:

ArrayList listednames = new ArrayList<>(); 

while (true) { 
    String entry = JOptionPane.showInputDialog("name:"); 
    if (entry == null) { 
     break; 
    } 
    entry = entry.trim(); 

    if (entry.equalsIgnoreCase("stop")) { 
     break; 
    } 
    if (entry.isEmpty()) { 
     continue; 
    } 
    if (listednames.contains(entry.toUpperCase())) { 
     continue; 
    } 

    listednames.add(entry.toUpperCase()); 
    Collections.sort(listednames); 
    String namen = listednames.toString(); 
    namen = namen.substring(1, namen.length()-1); 
    System.out.println(namen); 
} 
0

如果你喜歡它的短:

if (listednames.stream().anyMatch(entry::equalsIgnoreCase)) { 

雖然for循環通常更適合使用流來進行可讀性,性能和調試,只是認爲我會把它放在這裏。

而且因爲我喜歡更少的線(和你可能不知道這一點):

String entry = JOptionPane.showInputDialog("name:"); 
entry = Optional.ofNullable(entry).orElse("STOP").trim(); 
if ("STOP".equalsIgnoreCase(entry)) { 
    break; 
}