Reputation:
I have a string:
string[] = {"[","hey", "," , "how", ",", "are", ",", "you", "]" }
I'm writing this to a hashmap, I want the for loop to ignore all the commas. I tried something like this:
for(int i = 0; i<map.size(); i++){
if(string[i].equals(",")){
break;
}
System.out.println(map.get(string[i]));
}
I know it breaks after the first comma.
output is like : [ hey
I want the output to be: hey how are you
How to solve this?
How can I write something this: if(!string[i].equals(",") && !string[i].equals("[") && !string[i].equals("]"))
Upvotes: 0
Views: 86
Reputation: 6077
Instead of break
, you should use continue
.
continue
will skip the rest of the lines, and move to the next iteration of the loop. Hence, the rest of the data will be written in the hashmap.
I guess that you want to skip the characters that are not letters. In that case, you can do:
if(!Character.isLetter(string[i].charAt(0))){
continue;
}
This will skip all those characters which are not letters.
Upvotes: 0
Reputation: 470
I'm personally not a big fan of continue
and break
.
I think
for(int i = 0; i<map.size(); i++){
if(!string[i].equals(",")){
System.out.println(map.get(string[i]));
}
}
is more linear.
Upvotes: 0