Question: explain the code in detail, specifically the cipher method Convert all letters to a lowercase Encode each letter by shifting it the right amount using
explain the code in detail, specifically the cipher method
- Convert all letters to a lowercase
- Encode each letter by shifting it the right amount using the key, and display the encoded letters into a console window.
- Encodeeach digit (0 ~ 9) with its ASCII value shifted by the negative value of the key (1 -> 49-key, 0-> 48-key), and display the encoded digits into a console window.
- Skip all the punctuation marks, blanks, and anything else other than letters and digits and do NOT display them in a console window.
import java.util.*; // for Scanner public class Cipher { public static void main (String [] args) { Scanner console = new Scanner (System.in); System.out.print ("Your Message? ");//asks for message String message = console.nextLine(); System.out.print ("Encoding Key? ");//asks for the key int key = console.nextInt(); Cipher.cipher(message, key); } public static void cipher(String message, int key) {//takes in 2 parameters StringBuilder encodedMessage = new StringBuilder(); for (char a : message.toLowerCase().toCharArray()) {//changes to lowercase if (Character.isLetter(a)) { //shifts the letter depending on the input key int encodedChar = a + key % 26; if (encodedChar > 'z') { encodedChar -= 26; } encodedMessage.append((char) encodedChar); } else if (Character.isDigit(a)) { int encodedDigit = (a- '0' - key + 10) % 10 + '0'; encodedMessage.append((char) encodedDigit); } } System.out.println("Your message: " + encodedMessage.toString()); } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
