java - How to find the most common character in a String -
i have quick question. how find common character in string in java. know logically how it, not sure if syntax in correct:
public class helloworld { public static void main(string[] args){ string votes = "abbab"; char[] storingarray = votes.tochararray(); int numofb = 0; int numofa = 0; if (storingarray.contains("a")) { numofa++; } else if (storingarray.contains("b")) { numofab++; } if (numofa = numofb) { system.out.println("tie"); } else if (numofa > b) { system.out.println("a"); } else { system.out.println("b"); } } }
could me how correctly in java?
you can not compare char array string, below logic should work , give need:
public static void main(string[] args){ string votes = "abbab"; char[] storingarray = votes.tochararray(); int numofb = 0; int numofa = 0; for(char c : storingarray) { if(c == 'a') { numofa++; } if(c == 'b') { numofb++; } } if (numofa == numofb) { system.out.println("tie"); } else if (numofa > numofb) { system.out.println("a"); } else { system.out.println("b"); } }
there couple of mistakes in code:
- you can not use
if (numofa = numofb)
not valid expression. should use==
compare - you can not compare char array
contains
method. should used onstring
object
Comments
Post a Comment