-5

I have a already sorted string array named arr and Supposing I enter the sentence

hello how hello to how me in

Desired Output is

hello 2
how 2 
me 1 
in 1 
to 1

Here's how I am trying to count it

int counter = 1;
for(j1 = 0; j1 < arr.length; j1++){
   if(j1 + 1 < arr.length){
      if(arr[j1].equals(arr[j1 + 1])){
         counter++;
      } else {
         System.out.println(arr[j1] + " " + counter);
         counter = 1;
      }
   }
}

but this is not working , please help?

Suvarna Pattayil
  • 5,136
  • 5
  • 32
  • 59
Sigma
  • 742
  • 2
  • 9
  • 24

1 Answers1

1

The problem is the line:

if(j1 + 1 < arr.length) {...}

You are not iterating over the whole array; the last element is left uncounted. Without explaining to much, this could be a quick fix:

    public static void main(String[] args) {

    String[] arr = { "hello", "how", "hello", "to", "how", "me", "in" };
    Arrays.sort(arr);

    int counter = 1;
    for (int j1 = 0; j1 < arr.length; j1++) {

        int j2 = j1 + 1;
        String next = (j2 < arr.length) ? arr[j2] : null;

        if (arr[j1].equals(next)) {
            counter++;
        } else {
            System.out.println(arr[j1] + " " + counter);
            counter = 1;
        }
    }       
}
mrak
  • 2,826
  • 21
  • 21