Week-2 Assignment
Assignment: "Basic Text Encoder and Decoder"
Objective: Create a simple Java program to encode and decode text using
a shift-based cipher (similar to a Caesar cipher). This will help you practice
using loops, conditionals, and basic string manipulation in Java.
Program:
import java.util.Scanner;
public class ShiftCipher {
// Method to encode the text
public static String encode(String text, int shift) {
StringBuilder encoded = new StringBuilder();
for (char character : text.toCharArray()) {
if (Character.isLetter(character)) {
char base = Character.isLowerCase(character) ? 'a' : 'A';
// Shift the character and wrap around using modulo
char shifted = (char) ((character - base + shift) % 26 + base);
encoded.append(shifted);
} else {
// Non-letter characters are added unchanged
encoded.append(character);
}
}
return encoded.toString();
}
// Method to decode the text
public static String decode(String text, int shift) {
return encode(text, 26 - shift); // Decoding is just encoding with the
inverse shift
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to the Shift Cipher Program!");
System.out.print("Enter the shift value (1-25): ");
int shift = scanner.nextInt();
scanner.nextLine(); // Consume the newline character
System.out.print("Enter the text to encode: ");
String textToEncode = scanner.nextLine();
String encodedText = encode(textToEncode, shift);
System.out.println("Encoded Text: " + encodedText);
System.out.print("Enter the text to decode: ");
String textToDecode = scanner.nextLine();
String decodedText = decode(textToDecode, shift);
System.out.println("Decoded Text: " + decodedText);
scanner.close();
}
}
Output:
Welcome to the Shift Cipher Program!
Enter the shift value (1-25): 3
Enter the text to encode: "Hello, World!"
Encoded Text: "Khoor, Zruog!"
Enter the text to decode: "Khoor, Zruog!"
Decoded Text: "Hello, World!"
Output Screenshot: