它没有遍历代码中的if循环。
所需的o / p为:
This is real project with problems problems are tough to solve
我的代码:
public static void main(String[] args) {
String s = "This is real project with real problems real problems are tough to solve";
String key = "real";
int count = 0;
Map<Integer, String> map = new HashMap<Integer, String>();
StringTokenizer st = new StringTokenizer(s);
Integer v = null;
String next;
while (st.hasMoreElements()) {
next = st.nextToken();
// To assign unique key to the value in the string
if (v == null)
v = 1;
else
v++;
map.put(v, next);
}
System.out.println("before: " + map);
System.out.println(count);
//To delete the word "real" from the string
for (int i = 0; i <= map.size(); i++) {
//This is not working
if (map.containsValue("real") && count >= 1) {
//To delete value in the hashMap with ""
next = "";
}
count++;
}
System.out.println("After deleting: " + map );
}
最佳答案
我不知道您想在循环中做什么。但是,如果我了解您的要求,则应该这样做:
for (int i = 1; i <= map.size(); i++) {
if ("real".equals(map.get(i)) && count++ >= 1) {
map.remove(i);
}
}
输出:
After deleting: {1=This, 2=is, 3=real, 4=project, 5=with, 7=problems, 9=problems, 10=are, 11=tough, 12=to, 13=solve}