Reputation: 75
Original Question (Problem 3)
I'm completing a problem for class that requires converting a string message from ascii with a key to a decoded String message. I've tried both accessing the string from message.charAt(i) and by converting it to a char array but both times I get this weird out put on the console.
This is the method I have running
public static char[] decrypt(String message) {
char[] decoded = new char[message.length()];
char[] newmessage = message.toCharArray();
int ascii;
for(int key=0; key<=100; key++) {
for(int i=0; i<message.length(); i++) {
ascii = ( (int)newmessage[i] + 127) - 32;
if(ascii > 126)
decoded[i] = (char)((int)newmessage[i] - key);
else
decoded[i] = (char)((((int)newmessage[i] - key) +127) -32);
}
}
System.out.println(decoded);
return decoded;
}
This is where I called it in main
System.out.println("Problem 3");
String message = ":mmZ\\dxZmx]Zpgy";
System.out.println("Message Received: ");
System.out.println(message);
decrypt(message);
I can't seem to figure out where I went wrong with it. The expected output is for each key to be printed with the corresponded decoded message. The 88th key will show the message is "Attack at Dawn!".
Upvotes: 1
Views: 5639
Reputation: 2608
Okey first you need to now wich Key decode the message of :mmZ\\dxZmx]Zpgy
So for go for the easy part try to decode first the Hey
message with your algorithm that you made, and you forgot the most escenssial part:
if(originalChar + key > 126) then
EncryptedChar = 32 + ((originalChar + key) - 127)
else
EncryptedChar = (originalChar + key)
So you in your if statement you are missing the minus key
if(ascii - key > 126)
Always go and re read your question.
for(int key=0; key<=100; key++) {
for(int i=0; i<message.length(); i++) {
ascii = ( (int)newmessage[i] + 127) - 32;
if(ascii - key > 126)
decoded[i] = (char)((int)newmessage[i] - key);
else
decoded[i] = (char)((((int)newmessage[i] - key) +127) -32);
}
System.out.println("Decoded with i=" +key +":"+new String(decoded)); // For check what is the correct message.
}
Spoiler The MEssage is: Attacck at dawn!
Upvotes: 1
Reputation: 18864
If all you need is decode from ASCII to Java String, then one of correct ways of doing it is
char [] output = StandardCharsets.US_ASCII.decode(ByteBuffer.wrap(input)).array();
Based on your performance requirements, you may want to preallocate buffers, and may be the decoder (in the above example Charset::decode will create one on the fly).
Upvotes: 2