Reputation: 25
So the question is to write a java program that will get a String and a Character from input and it will encode it using a method like this:
Encoding method: the method will calculate the distance between the input character and the first letter of input string and add the input character to the beginning of that string and it will shift the rest of the letters of input based on the distance number.
example1: String --> Ali & Char --> D
Distance between D and A --> 3
Result: DAol
example2: String --> Test & Char --> R
Distance between R and T --> -2
Result: RTcqr
The program should also be able to decode the input.
example1: DAol --> Ali
example2: RTcqr --> Test
I tried this for Encoding but it didn't work.
public static void encode() {
String text = "Ali";
String result1 = "";
String result2 = "";
String finalResult = "";
char add = 'D';
char[] chars = {'a', 'b' ,'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
int dis = add - result1.charAt(0);
result2 += add;
result2 += result1;
for (int i = 0; i < result2.length(); i++) {
if (i < 2) {
finalResult += result2.charAt(i);
} else {
int temp = result2.charAt(i) + dis;
System.out.println("temp: "+temp);
finalResult += chars[i];
}
}
System.out.println(dis);
System.out.println(finalResult);
}
Upvotes: 0
Views: 844
Reputation: 2621
You don't need to define characters if you don't want to use any encoding private key. Below code works fine, you can follow the steps.
public class Main {
public static void main(String []args){
String test = "Ali";
char encoder = 'D';
String encoded = encode(test, encoder);
System.out.println(encoded);
System.out.println(decode(encoded));
test = "Test";
encoder = 'R';
encoded = encode(test, encoder);
System.out.println(encoded);
System.out.println(decode(encoded));
}
private static String encode(String text, char encoder){
char firstChar = text.charAt(0);
int distance = encoder - firstChar;
String encoded = "" + encoder + firstChar;
for(int i = 1; i < text.length(); i++){
encoded += (char)(text.charAt(i) + distance);
}
return encoded;
}
private static String decode(String text){
char encoder = text.charAt(0);
char firstChar = text.charAt(1);
int distance = encoder - firstChar;
String decoded = "" + firstChar;
for(int i = 2; i < text.length(); i++){
decoded += (char)(text.charAt(i) - distance);
}
return decoded;
}
}
Output:
DAol
Ali
RTcqr
Test
Upvotes: 1