27-class-example-caesar-cipher

27-class-example-cae - Encrypts a string by adding the value of key to each character The first line makes sure that key is always positive by

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

View Full Document Right Arrow Icon
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);
Background image of page 1
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

This note was uploaded on 10/14/2010 for the course CS 106A taught by Professor Sahami,m during the Fall '08 term at Stanford.

Ask a homework question - tutors are online