Friday, September 9, 2022

Alternate letters in uppercase in Java

A str‌ing (only alphabets) is passed as input.
The printed output should contain alphabets in odd positions in each word in uppercase and alphabets in even positions in a word in lowercase.

Example input/output1:

If the input is 'tREE GiVES us fruiTS', the output should be 'TrEe GiVeS Us FrUiTs

If the input is 'FLoweR iS beauTIFUL', the output should be 'FlOwEr Is BeAuTiFuL

Solution:

           import java.util.*;

  class Hello {

  public static void main(String[] args) {

  Scanner sc=new Scanner(System.in);

  String str=sc.nextLine();

  String[] input=str.split("[ ]");

  char[] ch=new char[str.length()];

  int i,j;

  for(i=0;i<input.length;i++)

  {

      ch=input[i].toCharArray(); 

     for(j=0;j<ch.length;j++)

     {

         if(j%2==0)

          System.out.print(Character.toUpperCase(ch[j]));

          else if(j%2==1)

          System.out.print(Character.toLowerCase(ch[j]));

     }

     System.out.print(" ");

  }

No comments:

Post a Comment

MFIB Comma Separated Integers

Fill in the blanks with code so that the program must accept three integers separated by a space and print them separated by a comma as the ...