{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

27-class-example-caesar-cipher

# 27-class-example-caesar-cipher - Encrypts a string by...

This preview shows page 1. Sign up to view the full content.

Handout #27 CS 106A July 16, 2009 Solution to the Caesar Cipher Problem 1. Caesar cipher /* * File: CaesarCipher.java * ----------------------- * This program translates a line of text into its Caesar cipher * form. */ import acm.program.*; public class CaesarCipher extends ConsoleProgram { public void run() { println("This program uses a Caesar cipher for encryption."); int key = readInt("Enter encryption key: "); String plaintext = readLine("Plaintext: "); String ciphertext = encryptCaesar(plaintext, key); println("Ciphertext: " + ciphertext);
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: } /* * Encrypts a string by adding the value of key to each character. * The first line makes sure that key is always positive by * converting negative keys to the equivalent positive shift. */ private String encryptCaesar(String str, int key) { if (key < 0) key = 26 - (-key % 26); String result = ""; for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); if (Character.isLetter(ch)) { ch = (char) ('A' + (Character.toUpperCase(ch) - 'A' + key) % 26); } result += ch; } return result; } }...
View Full Document

{[ snackBarMessage ]}