Caesar Cipher
Completed
Read a shift k (0–25) and a line. Shift every letter k places forward, wrapping around and keeping case. Other characters stay the same.
Input
Line 1: k. Line 2: the text.
Output
The encoded text.
Example
Input
3 Hello, World!
Output
Khoor, Zruog!
Editor
Java
Hints
c - 'a' gives the letter's position 0-25.
Add k, take % 26, then add 'a' back and cast to char.
Solution explanation
Arithmetic on char values gives an int, so cast the result back to char.
Show solution
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int k = Integer.parseInt(sc.nextLine().trim());
String text = sc.nextLine();
StringBuilder out = new StringBuilder();
for (char c : text.toCharArray()) {
if (Character.isUpperCase(c)) {
out.append((char) ('A' + (c - 'A' + k) % 26));
} else if (Character.isLowerCase(c)) {
out.append((char) ('a' + (c - 'a' + k) % 26));
} else {
out.append(c);
}
}
System.out.println(out);
}
}