← All resources

Class 11 and 12: Write a program to input a string and encode it by moving each alphabet 'n' places forward in a circular manner.

Where n is any number between 1 – 26

In circular forward encoding if on encoding the program crosses 'z' then it will go back to 'a'. Example: If 'x' has to be encoded 5 places forward then it will be as follows x->y->z->a->b->c.
OUTPUT:
Enter a String:
This is a new program
Enter a number:
5
The new string is: Ymnx nx f sjb uwtlwfr
import java.util.*;
class string_Encode
{
    public static void main()
    {
        Scanner sc=new Scanner(System.in);
        String s,s2="";
        int i, l, d, n;
        char ch;
        System.out.println("Enter a String: ");
        s=sc.nextLine();
        System.out.println("Enter a number between 1 to 26: ");
        n=sc.nextInt();
        if(n<1||n>26)
        {
            System.out.println("Invalid!!!");
            return;
        }
        l = s.length();
        for(i=0;i<l;i++)
        {
            ch = s.charAt(i);
            if(ch>='A'&&ch<='Z')
            {
                d = ch+n;
                if(d>90)
                d=d-26;
                ch = (char)d;
            }
            else if(ch>='a'&&ch<='z')
            {
                d = ch+n;
                if(d>122)
                d=d-26;
                ch = (char)d;
            }
            s2 = s2+ch;
        }
        System.out.println("The new string is: "+s2);
    }
}