Encoding a String using ASCII Characters in Java

Write a program to accept a sentence, and encode it by replacing each alphabet by its ASCII code and each blank by reversing its ASCII code.

Program:

import java.io.*;
class ASCII{
    public static void main(String args[])
    throws IOException{
        InputStreamReader in = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(in);
        System.out.print("Enter the sentence: ");
        String s = br.readLine();
        String a = new String();
        int rev = reverse(' ');
        int i = 0;
        for(i = 0; i < s.length(); i++){
            char ch = s.charAt(i);
            if(Character.isLetter(ch))
                a += (int)ch;
            else if(ch == ' ')
                a += rev;
            else
                a += ch;
        }
        System.out.println("Encoded string: " + a);
    }
    public static int reverse(int n){
        int rev = 0;
        while(n != 0){
            int rem = n % 10;
            rev = rev * 10 + rem;
            n /= 10;
        }
        return rev;
    }
}

Leave a Reply