如何将用户输入的字符串与数组列表进行比较,然后从数组列表中删除用户字符串字母,这是我的代码:
我想获取用户输入的字符串,例如Apple,然后我要从数组列表中删除字母“ a”,“ p”,“ l”,“ e”。
public static void playgame() {
ArrayList<String> obj = new ArrayList<String>(
Arrays.asList("a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z"));
while(!obj.isEmpty()) {
System.out.println(name1 + " enter your word:");
String word1 = reader.nextLine().toLowerCase();
System.out.println("Enter (y) yes if both players agree on the word and (n) no word is incorrect");
String y = reader.next();
String yes = "y";
String no = "n";
if(y.equals(yes)) {
countScore1++;
char[] wordToString = word1.toCharArray();
System.out.println(wordToString.length);
for(int i=0;i<wordToString.length;i++) {
String output=Character.toString(wordToString[i]);
System.out.println(output);
if(obj.contains(output)){
obj.remove(output);
}
}
System.out.println("Alphabet letters left:" + obj);
System.out.println("Correct word #######");
}
答案 0 :(得分:0)
请参阅Andy Turner关于单个字符串的消息。实际上,替换
ArrayList<String> obj = new ArrayList<String>(
Arrays.asList("a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z"));
例如与此
List<String> obj = new ArrayList<String>();
for(char c = 'a'; c <= 'z'; c++) {
obj.add(String.valueOf(c));
}
但是,我将使用HashSet而不是ArrayList。我猜HashSet在查找要删除的项目时具有更快的查找算法。
Set<String> obj = new HashSet<String>();
for(char c = 'a'; c <= 'z'; c++) {
obj.add(String.valueOf(c));
}