Computer Science, asked by nihal0077, 3 months ago

Write a program in Java to input a String and print only those words which have at least one pair of consecutive letters.

Example -

input - Understanding is very important.
output - Understanding


Don't Spam!!!​

Answers

Answered by Oreki
3

Program

import java.util.Scanner;

import java.util.StringTokenizer;

public class ConsecutiveLetters {

   static boolean hasConsecutiveLetter(String word) {

       for (int i = 0; i < word.length( ) - 1; i++)

           if (word.charAt(i) + 1 == word.charAt(i + 1))

               return true;

       return false;

   }

   public static void main(String[ ] args) {

       System.out.print("Enter a sentence - ");

      for (var st = new StringTokenizer(

               new Scanner(System.in).nextLine( )); st.hasMoreTokens( ); ) {

           String word = st.nextToken( );

           if (hasConsecutiveLetter(word))

               System.out.println(word);

       }

   }

}

StringTokenizer class

It allows us to break a string into tokens or simply put, into words separated by space. It is an easy way to break a String.

  • boolean hasMoreTokens( ) - checks if there are any further tokens/words accessible.
  • String nextToken( ) - returns the succeeding token/word from the String passed.

Algorithm

  • Accepting the sentence from the user using Scanner class.
  • Breaking the sentence into separate words using StringTokenizer class of java.util package.
  • Checking if any word word has consecutive letters in it.
  • Printing the acceptable words.
Attachments:
Similar questions