The method longestStreak is intended to determine the longest substring of consecutive identical characters in the parameter str and print the result.

For example, the call longestStreak("CCAAAAATTT!") should print the result "A 5" because the longest substring of consecutive identical characters is "AAAAA".

Complete the method below. Your implementation should conform to the example above.

public static void longestStreak(String str)

Respuesta :

public class JavaApplication72 {

   public static void longestStreak(String str){

       char prevC = '_';

       String largest = "";

       String txt = "";

       for (int i = 0; i < str.length(); i++){

           char c = str.charAt(i);

           if (c != prevC){

               txt = "";

           }

           txt += c;

           if (txt.length() > largest.length()){

                   largest = txt;

           }

           

           prevC = c;

       }

       System.out.println(largest.charAt(0)+" "+largest.length());

   }

   public static void main(String[] args) {

       longestStreak("CCAAAAATTT!");

   }

   

}

A Method in java is a block of named statements, that can be executed by simply calling it.

The method longestStreak in Java is as follows where comments are used to explain each line is as follows:

public static void longestStreak(String str){

   //This initializes the initial character to an empty character

   char previousChar = ' ';

   //This initializes the current and the longest streak to an empty string

   String largestStreak = "", currentStreak = "";

   //This iterates through the string

   for (int i = 0; i < str.length(); i++){

       //This checks if the current character and the previous character are not the same

       if (str.charAt(i) != previousChar){

           //If yes, the streak is reset

           currentStreak = "";

       }

       //The streak continues here

       currentStreak += str.charAt(i);

       //This checks the length of the longest streak

       if (currentStreak.length() > largestStreak.length()){

           largestStreak = currentStreak;

       }

       //This sets the previous character to the current character

       previousChar = str.charAt(i);

      }

      //This prints the longest streak and its length

      System.out.println(largestStreak.charAt(0)+" "+largestStreak.length());

  }

At the end of the method, the longest streak and its length, are printed.

See attachment for sample run

Read more about similar programs at:

https://brainly.com/question/13464860

Ver imagen MrRoyal