Go to Top

Monday, 3 October 2011

Toggle case

Question 54 : Write a program in Java to toggle the case of a string taken as input from the user.

Sample input : JavA

Sample output : jAVa

Java Program :

import java.io.*;
class toggle_case
{
 static void main()throws IOException
 {
     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
     int i,s,k=0;
     String a;
     System.out.print("Enter a string : ");
     a=br.readLine();
     System.out.print("\nToggled cases are : ");
     for(i=0;i<=a.length()-1;i++)
     {
         s=(int)a.charAt(i);
         if(s!=' ')
         {
             if(s>=65 && s<=90)
             k=s+32;
             if(s>=97 && s<=122)
             k=s-32;
             System.out.print((char)k);
            }
            else
            System.out.print(" ");
        }
        System.out.print("\n");
        System.out.println("\nThank you for using this short program");
    }
}

     

4 comments:

  1. please explain this condition. if(s!=' ')?

    ReplyDelete
    Replies
    1. It is required for the situation when s.charAt reads a space.if this condition won't be there then in the output spacewill not be printed.
      For eg:-
      Input: Hello World
      Output: hELLOwORLD

      But in this very program this condition is not required since s is also being checked for it's unicode.

      If the programer would have used Character.isUpperCase Or Character.isLowerCase..only then that condition would have been required.
      Thank You

      Delete

ShareThis