Nuwanda Nuwanda - 5 months ago 23
Java Question

skip multiple characters while adding to a hashmap in for loops

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("]"))

Answer

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.


Edit:

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.

Comments