The decoder works by taking each letter in a string and adding 13 to it..so a be
ID: 3565265 • Letter: T
Question
The decoder works by taking each letter in a string and adding 13 to it..so a becomes n..etc..I need one that generalizes that by instead of adding 13, it adds any given amount..Please complete by the instructions in the comments..Also, you should not encode the spaces!!
import java.util.Scanner;
public class StringEncoder {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (true) {
System.out.println("Enter string to be encoded. q to quit");
String line = in.nextLine();
if (line.equals("q")) break;
System.out.println("Enter encoding key.");
int key = in.nextInt();
in.nextLine(); // read and discard enter key
String estr = encode(line, key);
System.out.println("Secret message: "+estr);
String dstr = encode(estr, -key);
System.out.println("Original message: "+dstr);
}
System.out.println("bye.");
}
public static String encode(String str, int key) {
// examine each character in the string
// determine if it is lowercase, uppercase or something else
String result="";
// use a loop
// for each character in the string
// if the character is a letter a-z or A-Z
// add the key value to the character
// if the new value is greater than z or Z, then wrap around
// if new value if lower than a or A, then wrap around
// append translated charater to result string
return result;
}
}
Explanation / Answer
import java.util.Scanner;
public class StringEncoder {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (true) {
System.out.println("Enter string to be encoded. q to quit");
String line = in.nextLine();
if (line.equals("q")) break;
System.out.println("Enter encoding key.");
int key = in.nextInt();
in.nextLine(); // read and discard enter key
String estr = encode(line, key);
System.out.println("Secret message: "+estr);
String dstr = encode(estr, -key);
System.out.println("Original message: "+dstr);
}
System.out.println("bye.");
}
public static String encode(String str, int key)
{
String result = "";
key = key%26;
int index = 0;
while(index < str.length())
{
char curChar = str.charAt(index);
if ('a' <= curChar && curChar <= 'z' )
{
int convertedChar = curChar + key;
if (convertedChar > 'z')
{
convertedChar = (convertedChar - 'z') + 'a' - 1;
}
else if (convertedChar < 'a')
{
convertedChar = 'z' - ('a' - convertedChar) + 1;
}
result = result + (char)convertedChar;
}
else if ('A' <= curChar && curChar <= 'Z' )
{
int convertedChar = curChar + key;
if (convertedChar > 'Z')
{
convertedChar = (convertedChar - 'Z') + 'A' - 1;
}
else if (convertedChar < 'A')
{
convertedChar = 'Z' - ('A' - convertedChar) + 1;
}
result = result + (char)convertedChar;
}
else
{
result = result + (char)curChar;
}
index = index + 1;
}
return result;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.