Secret Code

From CompSciWiki
Revision as of 12:08, 1 April 2010 by DavidG (Talk | contribs)

Jump to: navigation, search

The following string of text has a secret code encrypted inside it. In order to decipher it, you will need to: 1) Extract every fourth letter of the string 2) Reverse the order of the extracted letters 3) Set the case of the extracted letters so that they alternate between uppercase and lowercase,

  with the first letter being uppercase.
  

The following is the string that must be deciphered:

xmydartlkarrsgeoptwwjvbodeblxgbleivetoihewt

To solve this problem: You will need three string variables: - one called "message" to store the above string to be deciphered - one called "result1" to store the result after Step 1 - one called "secretCode" to store the results after Steps 2 and 3

To extract every fourth letter, you will need the length method, charAt() method, a while loop, a counter, and the "message" and "result1" string variables.

To reverse the order of the letters, you will need the length() and charAt() methods, a while loop, and the "result1" and "secretCode" string variables.

Note that because the first char in a string is index 0, the last char will actually be length - 1. For example, a string with 5 chars the indexes will be from 0 to 4.

To alternate the cases, you will need the length(), charAt(), toLowerCase(), and toUpperCase() methods, a while loop, and the "secretCode" string variable.


Solution

public class DecodeMessage { public static void main(String[] args) { String message; String result1 = ""; String password = ""; int counter = 4;

message = "xmydartlkarrsgeoptwwjvbodeblxgbleivetoihewt";

//extract every fourth letter while(counter < message.length) { result1 += message.charAt(counter); counter += 4; }


//reset counter to end of result1 counter = result1.length - 1;

//traverse result1 from the end to the beginning and store the letters in password while(counter >= 0) { password += message.charAt(counter); counter--; }

//alternate the cases in result 2. Counter is now at 0 so it doesn't need to be reset while(counter < password.length) { if(counter%2 == 0) { password.charAt(counter).toUpperCase(); } counter++; } } }

The final output (ie. the secret code) should be HeLlOwOrLd