I am working on a project and the problem asks me to switch specific letters in an array. For example, a goes to z, b to y, c to x etc...
I wrote this:
import java.util.Scanner;
public class Project1
{
public static void main( String [] args )
{
System.out.println("This program helps to encode or decode some text, the concept is that an A turns into a Z, B into a Y etc.");
Scanner reader = new Scanner ( System.in );
System.out.print("What is your message (encoded or not): ");
String Sentence = reader.nextLine();
System.out.println();
System.out.print("Press 1 to encode and 2 to decode: ");
int Number = reader.nextInt();
if ( Number == 1)
{
Encode (Sentence);
}
else if ( Number == 2)
{
Decode (Sentence);
}
else
{
System.out.println("The number has to be 1 or 2.");
}
}
public static void Encode (String a)
{
a = a.replace( 'a' , 'z' );
a = a.replace( 'b' , 'y' );
a = a.replace( 'c' , 'x' );
a = a.replace( 'd' , 'w' );
a = a.replace( 'e' , 'v' );
a = a.replace( 'f' , 'u' );
a = a.replace( 'g' , 't' );
a = a.replace( 'h' , 's' );
a = a.replace( 'i' , 'r' );
a = a.replace( 'j' , 'q' );
a = a.replace( 'k' , 'p' );
a = a.replace( 'l' , 'o' );
a = a.replace( 'm' , 'n' );
a = a.replace( 'n' , 'm' );
a = a.replace( 'o' , 'l' );
a = a.replace( 'p' , 'k' );
a = a.replace( 'q' , 'j' );
a = a.replace( 'r' , 'i' );
a = a.replace( 's' , 'h' );
a = a.replace( 't' , 'g' );
a = a.replace( 'u' , 'f' );
a = a.replace( 'v' , 'e' );
a = a.replace( 'w' , 'd' );
a = a.replace( 'x' , 'c' );
a = a.replace( 'y' , 'b' );
a = a.replace( 'z' , 'a' );
System.out.println("Encoded message is: " + a);
}
public static void Decode ( String s)
{
s = s.replace( 'z' , 'a' );
s = s.replace( 'y' , 'b' );
System.out.println("Decoded message is: " + s);
}
}
However, when I put in a word with an a it is turned into a z and then back into and a again. I was wondering if there was any other way to switch from one letter to another like this so that the problem does not happen again.
I think the easiest way is to iterate through your String
, changing each character individually. It may be easiest to do this in a char[]
, which you can convert back into a String
at the end.
Also, you don't need separate encode
and decode
methods, since encoding and decoding a String
is exactly the same transformation.
public String encode(String toEncode) {
char[] characters = toEncode.toCharArray();
for (int index = 0; index < characters.length; index++) {
if (characters[index] >= 'a' && characters[index] <= 'z') {
characters[index] = (char)('a' + 'z' - characters[index]);
}
}
return new String(characters);
}
Notice the char
arithmetic in the middle there, which will translate a
to z
, b
to y
and so on. The if
condition ensures that you don't replace any characters that aren't lower case letters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With