Computer Applications

Write a program by using a class in Java with the following specifications:

Class name — Stringop

Data members:

  1. String str

Member functions:

  1. Stringop() — to initialize str with NULL
  2. void accept() — to input a sentence
  3. void encode() — to replace and print each character of the string with the second next character in the ASCII table. For example, A with C, B with D and so on
  4. void print() — to print each word of the String in a separate line

Java

Java Constructors

37 Likes

Answer

import java.util.Scanner;

public class Stringop
{
    private String str;

    public Stringop() {
        str = null;
    }

    public void accept() {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a sentence: ");
        str = in.nextLine();
    }

    public void encode() {
        char[] arr = new char[str.length()];
        for (int i = 0; i < str.length(); i++) {
            arr[i] = (char)(str.charAt(i) + 2);
        }
        str = new String(arr);
        System.out.println("\nEncoded Sentence:");
        System.out.println(str);
    }

    public void print() {
        System.out.println("\nPrinting each word on a separate line:");
        int s = 0;
        while (s < str.length()) {
            int e = str.indexOf(' ', s);
            if (e == -1)
                e = str.length();
            System.out.println(str.substring(s, e));
            s = e + 1;
        }
    }
    
    public static void main(String args[]) {
        Stringop obj = new Stringop();
        obj.accept();
        obj.print();
        obj.encode();
    }
}

Variable Description Table

Program Explanation

Output

Answered By

9 Likes


Related Questions