Sneha 5 (Nis)

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

Name: Sneha Upadhyay

Roll no.: 30

Practical No. 5
Aim:

Write a program caeser cipher (crypted )

Program:
import java.util.Scanner;

public class CaesarCipher {

public static String caesarCipher(String text, int shift) {

StringBuilder result = new StringBuilder();

for (int i = 0; i < text.length(); i++) {

char ch = text.charAt(i);

if (Character.isLetter(ch)) {

if (Character.isUpperCase(ch)) {

char encryptedChar = (char) ((ch - 'A' + shift) % 26 + 'A');

result.append(encryptedChar);

} else if (Character.isLowerCase(ch)) {

char encryptedChar = (char) ((ch - 'a' + shift) % 26 + 'a');

result.append(encryptedChar);

} else {

result.append(ch);

return result.toString();
}

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the text to be encrypted: ");

String text = scanner.nextLine();

System.out.print("Enter the shift value: ");

int shift = scanner.nextInt();

String encryptedText = caesarCipher(text, shift);

System.out.println("Encrypted text: " + encryptedText);

scanner.close();

@Override

public String toString() {

return "CaesarCipher []";

Output:

You might also like