Write a java program to Count Sequential Characters.

Write Java code to count the number of characters which gets repeated 3 times consecutively and return that count (ignore case). Get a string as input. If no character gets repeated 3 times consecutively return -1.

The return type of the output is the repeat count.

Input and Output Format:

Input consists a string.

The output is an integer.

Refer sample output for formatting specifications.

Sample Input 1:

abcXXXabc

Sample Output 1:

1

Sample Input 2:

aaaxxyzAAAx

Sample Output 2:

2

Count Sequential Characters in Java.

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    String input1 = sc.nextLine();
    System.out.println(consecutiveRepeatitionOfChar(input1));
  }

  public static int consecutiveRepeatitionOfChar(String input1) {
    int c = 0;
    int n = 0;
    for (int i = 0; i < input1.length() - 1; i++) {
      if (input1.charAt(i) == input1.charAt(i + 1))
        n++;
      else
        n = 0;
      if (n == 2)
        c++;
    }
    return c;
  }
}

Add a Comment

Your email address will not be published. Required fields are marked *

seven + one =