Secret Code

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

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
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 intermediate result - one called "secretCode" to reverse the order of the letters in "result1".

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

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

Note that because the first char in a string is index 0, the last char will actually be length - 1. For example, for 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" variable.


Solution

public class DecodeMessage { public static void main(String[] args) { String message; String result1 = ""; String secretCode= ""; 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) { secretCode+= result1.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) { secretCode.charAt(counter).toUpperCase(); } counter++; } } }

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