Difference between revisions of "Top Secret"

From CompSciWiki
Jump to: navigation, search
 
 
(16 intermediate revisions by 4 users not shown)
Line 1: Line 1:
 
{{1010PrAD|ProblemName=Top Secret
 
{{1010PrAD|ProblemName=Top Secret
  
|Problem= You are given an ordered array of Strings.  Your program will do a few things.  First, it must verify that the array is indeed ordered.  This will be done in a separate method, and the mothod will return a boolean value.  ('true' indicating that the array is ordered)  Second, if the array is ordered, then you must prompt the user to guess a word that might be in the array. This prompt will be done with JOptionPane.  Another method will then be required to conduct a binary search of the array to look for the user's guess. This method will also return a boolean indicating success or failure.  Finally, the user will only be allowed to guess a maximum of five times before the program will stop. <br \><br \>
+
|Problem= You are a software developer for CSIS (Canadian Security Inteligence Service) and you've been sent a secret message, but all of the software at your station has been deleted! However, this message is very important and must be decoded right away. That's where you come in. You will write a program that decodes the message, verifies the authenticity, then prints out the mission directive.
  
For output, the program will first print the array. Then it will print the status of the array. (whether it is ordered or not)  Then it will print out every guess the user makes. Finally, print out the user's number of attempts and whether they succeeded in entering a word that's in the array.<br \><br \>
+
First, the message is in a secret code. Every character is represented by a different character. The following arrays show the relationship. The first one is our alphabet, the second is the secret one.
  
Your output should look something like this: <br \>
+
char [] array1 = {'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','.','!',' '};<br>
<pre>
+
char [] array2 = {'l','x','g','r','j','w','!','i','q','a','t','z','.','s','y','k','e','o',' ','p','d','c','h','n','v','u','f','b','m'};
Array: "word1" "word2" "word3"
+
 
It is ordered.
+
<br><br>
Guess 1: blah
+
 
Guess 2: blah
+
 
Guess 3: word1
+
Once you've decoded the message, you'll have to verify it.  Every other character, starting with the first character, if put together, will form a palindrome.  You must write two methods: one that will form the palindrome out of the message, the other method to make sure that it is indeed a palindrome.
 +
 
 +
Once you've verified that, you'll need to get the mission instruction out of the message.  It is formed by taking every other letter starting with the second character of the decoded message. (I suggest making your method that takes every other character work for both palindrome and instruction)
 +
 
 +
There is one final verification needed.  The instruction must start with the phrase "top secret".  If not, it's a fake!  After you've determined that the instruction is the real deal, you have to print out just the mission instruction.  (Use substring to print out the message after the "top secret" part)
 +
<br><br>
  
The array contains "word1".
 
It took you 3 attempt(s) to get it.
 
</pre>
 
  
 
|SideSectionTitle=Problem Solving and Programming Examples
 
|SideSectionTitle=Problem Solving and Programming Examples
 
|SideSection=
 
|SideSection=
[[Image:Wiki_bench01.jpg|center]]
+
[[Image:Wiki_bench01.jpg|center]]<BR>
<BR>
+
  
 
|Solution=
 
|Solution=
Let's start first by putting together the main method.  When starting to write any section of code, we need to figure out what variables we will be using.  We need: one integer variable to store the maximum number of tries a user can guess; three boolean values, one to track whether the array is ordered or not, one to track whether the user has reached the max number of attempts, and one to track whether they entered a guess that was in the array; a String to hold the input entered by JOptionPane; another integer to track the number of attempts made by the user; and finally, our ordered array of Strings.  We'll place these at the top of our main method.  Remember to always initialise your variables!
 
  
<pre>
+
When you start working on your program, don't forget to copy in those two char arrays and secret message. 
final int MAX_TRIES = 5;
+
  
boolean done = false;
+
We'll start this program by first deciding what methods we will need (apart from main), and what the signatures of those methods will be.  This is an important step (especially during the exam) because it will prevent an unnecessary amount of erasing later on.  From the problem stated above, we realise we need 4 methods.  The first is to decode the message, and this one will have to be passed the secret message and the two char arrays.  It will be returning the decoded message as a String.  The second method is to take every other character, and combine them into a new String, which will be returned.  It needs to be passed the String to perform this on, and we will be passing it an integer value. (The reason for this will be mentioned later on)  The third method is to check the string produced by every even character to see if it's a palindrome.  This will be passed the string to be checked, and will return a boolean.  The fourth and last method is to check the string produced by every odd character to make sure it starts with the words "top secret".  It too will be passed the string to check and the string containing the key to look for (the words "top secret"), and return a boolean.
boolean found = false;
+
boolean inOrder = false;
+
String input = "";
+
int count = 0;
+
  
String [] ordered = {"a","cake","is","lie","the"};
 
  
</pre>
+
Now that we've decided that, let's get to programming.  First, I will make three calls from within main to get started.  Note the integer value in the last two method calls.  That's because in the "everyOther" method I use modulus to check for either odd or even numbered characters.  You'll see the code for this in a bit, but it allows us to re-use a method for performing similar operations.
  
Notice I used "final" and all caps for the maximum tries variable.  That's because this number is a constant, and will never change.
+
{{CodeBlock|Code=
 +
String result = decode(secretMessage, array1, array2);
 +
String palindrome = everyOther(result,0);
 +
String message = everyOther(result,1);
 +
}}
  
Now, the problem stated that we needed to print out the array's contents, which needs to be done in a method.  So I make the call to this non-existent method.  At this point, you can either jump ahead and write the body for this method, or continue writing out the main method.  While either strategy is fine, keep in mind that when writing an exam, you will be doing so in pencil.  If you don't leave yourself enough room, jumping ahead to write a method might leave you out of room for the main method.  I always like to write out a method as much as possible before going to the next one, so I will continue writing main.
 
  
Since we also need to know if the array is ordered or not, I will also make that non-existent call at this timeThis method will be returning a boolean, so I should make sure to store it.
+
Now we should code in our check for a palindrome with a simple if-else statementThe else should print out an error message, and will look something like this,
  
<pre>
+
{{CodeBlock|Code=
print(ordered);
+
if(checkPalindrome(palindrome))
inOrder = checkOrder(ordered);
+
{
</pre>
+
}
 +
else
 +
System.out.println("There was no palindrome.  This message is a fake!");
 +
}}
  
Now remember that if an array is not ordered, the binary search will not work.  So we should write an if-else statement that handles this.  Also, an appropriate error message is always useful.
 
  
<pre>
+
And within the "if" part, we will need to check the string made from all the odd numbered characters for the "top secret" string.  If there is no match, we print out an error message.  It it is a match, we will print out what the mission instruction is. (making sure we use substring to remove the "top secret" part out of the message)  This gives us the following.
if(inOrder)
+
 
 +
{{CodeBlock|Code=
 +
if(checkSecrecy(message, start))
 
{
 
{
 +
System.out.print("Your secret mission is: ");
 +
System.out.println(message.substring(start.length()+1,message.length()));
 
}
 
}
 
else
 
else
System.out.println("This array is not in order, I cannot search it.");
+
System.out.println("There was no \"top secret\".  This message is a fake!");
</pre>
+
}}
  
Now within the if part, we need to have code for getting the user to make guesses.  First we'll print a statement saying that the array is ordered.  Then we'll start our while loop, and the condition of the while will be dependent on our "done" boolean, as there are a few conditions that might kick us out of the loop.  So now we have:
 
  
<pre>
+
And that is it for our main method.  Now we will write code for our first method, the "decode" method.  As mentioned before, it is passed a String and two char arrays, and returns a String.  Within that method we'll declare and initialise our return variable right aways.  Now we have:
if(inOrder)
+
 
 +
{{CodeBlock|Code=
 +
public static String decode(String message, char [] array1, char [] array2)
 
{
 
{
System.out.println("This array is ordered.");
+
String result = "";
  
while(!done)
+
return result;
{
+
}
+
 
}
 
}
else
+
}}
System.out.println("This array is not in order, I cannot search it.");
+
</pre>
+
  
Within the while loop we will ask the user for input, store that input, incrememnt the number of guess the user has entered, and print out the guess.  Then we will conduct a search for the guess with another method call, which will be returning a boolean.  Finally, as in any while loop, we need to check if we should stop the loop.  The while loop should end if a guess was correct, or if the maximum number of guess has been reached.  The following code goes within the while loop.
 
  
<pre>
+
When coding, I always make sure to include the return statement as well, but you won't always be able to do this when writing an exam.  Now for decoding.  We will be using two for loops.  The outside loop is for iterating through every character in the string we need to decode, the inside loop is for iterating through every character in the second char array (secret code array). As for the decoding, we will be comparing the character in the string to characters in the second char array, and when we find a match, we take the subscript ("j") and take the character at that spot from the first array (english language array). We then append this character to our return string.  This gives us:
input = JOptionPane.showInputDialog("Enter the word you are looking for?",null);
+
count++;
+
System.out.println("Guess " +count +": " +input);
+
  
found = findString(input, ordered);
+
{{CodeBlock|Code=
 +
for(int i = 0; i < message.length(); i++)
 +
{
 +
for(int j = 0; j < array2.length; j++)
 +
{
 +
if(message.charAt(i) == array2[j])
 +
result += array1[j];
 +
}
 +
}
 +
}}
  
if(found || count == MAX_TRIES)
 
done = true;
 
</pre>
 
  
The final part for our main method is to print out whether the user has met with success or notWe use the "found" boolean for this and print a success message if "found" is true or a failure message if false.  We also need to print out how many attempts it took.
+
And our decoding is doneNow for getting every other character out of this string.  We decided earlier that we will pass it a string and an integer, and will be returning a String. So our method will look like this: (including return variable and return statement)
  
<pre>
+
{{CodeBlock|Code=
if(found)
+
public static String everyOther(String str, int num)
 
{
 
{
System.out.println("By Jove, the array contains " +input +"!");
+
String result = "";
System.out.println("It took you " +count +" attempt(s) to get it.");
+
 
}
+
return result;
else
+
{
+
System.out.println("By Jove, it took you " +count +" tries and you still didn't get it?");
+
 
}
 
}
</pre>
+
}}
  
And that is it for the main method!  We will now begin writing out the other methods, starting with the print method.  Now remember, our print method is not going to return anything and it needs to be passed a String array to print.  So the method header will be "public static void print(String [] array)".  In the method, we will first print out a title, then each individual element in our array.  A for loop is perfect for this job, since all we are doing is an array traversal.  Then we print out an empty line at the end to make the final print out prettier.
 
  
<pre>
+
Now we'll use a for loop for iterating through the string.  As I'm sure you've encountered before already, when checking for even or odd numbers, using modulus (%) is easiest. And that's also where that integer we passed in is being used. We'll check for odd or even by "modding" i by 2, and comparring it to the passed integer.  If i is equal to 0, it's even, otherwise, it's odd.  We'll build our string accordingly, and return it.  Here is an example of the loop with if statement.
public static void print(String [] array)
+
{
+
System.out.print("Array: ");
+
  
for(int i = 0; i < array.length; i++)
+
{{CodeBlock|Code=
System.out.print("\"" +array[i] +"\" ");
+
for(int i = 0; i < str.length(); i++)
 
+
{
System.out.println();
+
if(i % 2 == num)
 +
result += str.charAt(i);
 
}
 
}
</pre>
+
}}
  
Now for checking if an array is ordered.  Since this method is returning a boolean, we need to mention this in the method header.  Also, it will need to be passed an array to check, so the header will look like "public static boolean checkOrder(String [] array)".  We'll first create our return variable, and set it to false.  We'll use a for loop again for this, since we're traversing an array again.  Make sure that your loop stops one element sooner than the end, since we are checking the current element against the next, and we don't want any "out of bounds" errors.  In the loop, we'll be checking each element to see if it is "less" than the next one.  Since these are strings, we will need to use the "compareTo" method, and the result should come back as a negative number.  If "compareTo" doesn't return a negative number, than the array is not in order, and we need to set our return variable to false.  Once the array is checked, we return our result.  This gives us the folloing method.
 
  
<pre>
+
Now for checking the palindrome.  The method just needs a string, and will pass back a boolean variable.  We'll initialise the boolean variable to "true", since we will change it to "false" if at any point we notice the string is not a palindrome.  We'll also write in the for loop right aways as well.  The length of the loop is a bit different, since we just need to check half of the string.  (The last half should be the same as the first half, only in reverse)  So after cutting the length in half, our method so far will look like:
public static boolean checkOrder(String [] array)
+
 
 +
{{CodeBlock|Code=
 +
public static boolean checkPalindrome(String str)
 
{
 
{
 
boolean result = true;
 
boolean result = true;
  
for(int i = 0; i < array.length - 1; i++)
+
for(int i = 0; i < str.length() / 2; i++)
 
{
 
{
if(array[i].compareTo(array[i+1]) > 0)
 
result = false;
 
 
}
 
}
return result ;
+
 
 +
return result;
 
}
 
}
</pre>
+
}}
 +
 
  
Now for our binary searchThis method is also returning a boolean, and it will be sent an array of Strings as well as a String to search for. (the user's guess) The method header will be "public static boolean findString(String str, String [] array)". Now, unless your prof states otherwise, I highly suggest that you memorise how the binary search algorithm works.  It's a very important algorithm, and even if it doesn't get asked for on an exam, it is stil very useful to know for any future programming endeavours.  The biggest thing to note in this algorithm is that Strings can't be compared by using < or > signs.  So just use the "compareTo" method to make comparisons as you search.  Remember that String's "compareTo" method will return a negative value if the String before the "period" comes after the String in the brackets, and will return a positive value if the Strings are the other way around.
+
We'll check each character at position i against each character at position str.length() - i - 1We have to subtract 1 because just using str.length() - i will give us an error message. (It goes past the length of the string since we start counting from 0If those two characters don't match, we change our return boolean to "false".
  
<pre>
+
{{CodeBlock|Code=
public static boolean findString(String str, String [] array)
+
if(str.charAt(i) != str.charAt(str.length() - 1 - i))
 +
result = false;   
 +
}}
 +
 
 +
 
 +
For the last method, we need to check for "top secret".  We need to pass this method both the string to check in (the message), and the string to look for ("top secret").  This method will be returning a boolean.  We'll initialise our return boolean to "false", since we'll be turning it to "true" if the message contains the word we're looking for.  You may have noticed that our boolean initialisations are not the same.  One must give consideration as to what to initialise a boolean to.  In practise, a developer wants to "switch" a boolean as little as possible in code.  While it doesn't affect the computer or how it handles your program, it makes for more readable code, and gives it a cleaner look.  (In the case of this method, I opted to go from "false" to "true" so I could avoid using the "!" symbol at the beginning of a long if check)
 +
 
 +
{{CodeBlock|Code=
 +
public static boolean checkSecrecy(String message, String start)
 
{
 
{
boolean found = false;
+
boolean result = false;
int high;
+
int low;
+
int mid;
+
  
if(array != null)
+
return result;     
{
+
}
    high = array.length - 1;
+
}}
    low = 0;
+
  
    while(!found && high >= low)
 
    {
 
mid = (high + low) / 2;
 
  
if(array[mid].compareTo(str) < 0)
+
And the actual check itself is quite simple.  We'll be using substring again to pull out the beginning of the message, of a length equal to the second strings length.  Then we check the two against each other, and change our return variable to "true" if they match.
    low = mid + 1;
+
  
else if(array[mid].compareTo(str) > 0)
+
{{CodeBlock|Code=
    high = mid - 1;
+
if(message.substring(0,start.length()).equals(start))
 +
result = true;
 +
}}
  
else
 
    found = true;
 
    }
 
}
 
  
return found;
+
Our program is now complete.  I will leave it to you to write the program and discover what the secret message is. (Trust me, there is one)  Otherwise, you can also copy and paste the following program if you're really anxious to perform the secret task. 
}
+
 
</pre>
+
Also, for those curious, here is the palindrome used.  I had to remove the spaces so checking it in the program would be easier.
  
And that's all there is to it!  Whenever writing programs, always break up the problem into smaller pieces.  It makes programming (and exam writing) so much less stressfull.
+
"Are we not drawn onward, we few, drawn onward to new era?"
  
 
<br \><br \>
 
<br \><br \>
Line 172: Line 167:
  
 
|SolutionCode=
 
|SolutionCode=
 
+
public class TopSecret
<pre>
+
 
+
import javax.swing.*;
+
 
+
public class StringBinarySearch
+
 
{
 
{
 
public static void main(String [] args)
 
public static void main(String [] args)
 
{
 
{
final int MAX_TRIES = 5;
+
char [] array1 = {'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','.','!',' '};
 +
char [] array2 = {'l','x','g','r','j','w','!','i','q','a','t','z','.','s','y','k',
 +
                                  'e','o',' ','p','d','c','h','n','v','u','f','b','m'};
 +
String secretMessage = "lpoyjkhmj sjygporjoplmhksdy.s.hjlzomrghljow qjxhyrdomlhhqspyismh.llosrvpmypsqj.hxjqopl ";
  
boolean done = false;
+
String start = "top secret";
boolean found = false;
+
boolean inOrder = false;
+
String input = "";
+
int count = 0;
+
  
String [] notOrdered = {"the","cake","is","a","lie"};
+
String result = decode(secretMessage, array1, array2);
String [] ordered = {"a","cake","is","lie","the"};
+
String palindrome = everyOther(result,0);
 +
String message = everyOther(result,1);
  
print(ordered);
+
if(checkPalindrome(palindrome))
 
+
inOrder = checkOrder(ordered);
+
 
+
if(inOrder)
+
 
{
 
{
System.out.println("This array is ordered.");
+
if(checkSecrecy(message, start))
 
+
while(!done)
+
 
{
 
{
input = JOptionPane.showInputDialog("Enter the word you are looking for?",null);
+
System.out.print("Your secret mission is: ");
count++;
+
System.out.println(message.substring(start.length()+1,message.length()));
System.out.println("Guess " +count +": " +input);
+
 
+
found = findString(input, ordered);
+
 
+
if(found || count == MAX_TRIES)
+
done = true;
+
 
}
 
}
 +
else
 +
System.out.println("There was no \"top secret\".  This message is a fake!");
 
}
 
}
 
else
 
else
System.out.println("This array is not in order, I cannot search it.");
+
System.out.println("There was no palindrome.  This message is a fake!");
 +
}
  
 +
public static String decode(String message, char [] array1, char [] array2)
 +
{
 +
String result = "";
  
if(found)
+
for(int i = 0; i < message.length(); i++)
 
{
 
{
System.out.println("By Jove, the array contains " +input +"!");
+
for(int j = 0; j < array2.length; j++)
System.out.println("It took you " +count +" attempt(s) to get it.");
+
{
}
+
if(message.charAt(i) == array2[j])
else
+
result += array1[j];
{
+
}
System.out.println("By Jove, it took you " +count +" tries and you still didn't get it?");
+
 
}
 
}
 +
 +
return result;
 
}
 
}
  
public static void print(String [] array)
+
public static String everyOther(String str, int num)
 
{
 
{
System.out.print("Array: ");
+
String result = "";
  
for(int i = 0; i < array.length; i++)
+
for(int i = 0; i < str.length(); i++)
System.out.print("\"" +array[i] +"\" ");
+
{
 +
if(i % 2 == num)
 +
result += str.charAt(i);
 +
}
  
System.out.println();
+
return result;
 
}
 
}
  
public static boolean checkOrder(String [] array)
+
public static boolean checkPalindrome(String str)
 
{
 
{
 
boolean result = true;
 
boolean result = true;
  
for(int i = 0; i < array.length - 1; i++)
+
for(int i = 0; i < str.length() / 2; i++)
 
{
 
{
if(array[i].compareTo(array[i+1]) > 0)
+
if(str.charAt(i) != str.charAt(str.length() - 1 - i))
result = false;
+
result = false;  
 
}
 
}
return result ;
+
 
 +
return result;
 
}
 
}
  
public static boolean findString(String str, String [] array)
+
public static boolean checkSecrecy(String message, String start)
 
{
 
{
boolean found = false;
+
boolean result = false;
int high;
+
int low;
+
int mid;
+
  
if(array != null)
+
if(message.substring(0,start.length()).equals(start))
{
+
result = true;
    high = array.length - 1;
+
    low = 0;
+
  
    while(!found && high >= low)
+
return result;    
    {
+
mid = (high + low) / 2;
+
 
+
if(array[mid].compareTo(str) < 0)
+
    low = mid + 1;
+
 
+
else if(array[mid].compareTo(str) > 0)
+
    high = mid - 1;
+
 
+
else
+
    found = true;
+
    }
+
}
+
 
+
return found;
+
 
}
 
}
 
}
 
}
 
 
 
</pre>
 
 
 
}}
 
}}

Latest revision as of 17:07, 7 December 2011

Back to the Program-A-Day homepage

Problem

You are a software developer for CSIS (Canadian Security Inteligence Service) and you've been sent a secret message, but all of the software at your station has been deleted! However, this message is very important and must be decoded right away. That's where you come in. You will write a program that decodes the message, verifies the authenticity, then prints out the mission directive.

First, the message is in a secret code. Every character is represented by a different character. The following arrays show the relationship. The first one is our alphabet, the second is the secret one.

char [] array1 = {'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','.','!',' '};
char [] array2 = {'l','x','g','r','j','w','!','i','q','a','t','z','.','s','y','k','e','o',' ','p','d','c','h','n','v','u','f','b','m'};




Once you've decoded the message, you'll have to verify it. Every other character, starting with the first character, if put together, will form a palindrome. You must write two methods: one that will form the palindrome out of the message, the other method to make sure that it is indeed a palindrome.

Once you've verified that, you'll need to get the mission instruction out of the message. It is formed by taking every other letter starting with the second character of the decoded message. (I suggest making your method that takes every other character work for both palindrome and instruction)

There is one final verification needed. The instruction must start with the phrase "top secret". If not, it's a fake! After you've determined that the instruction is the real deal, you have to print out just the mission instruction. (Use substring to print out the message after the "top secret" part)

 

Problem Solving and Programming Examples

Wiki bench01.jpg

Solution

When you start working on your program, don't forget to copy in those two char arrays and secret message.

We'll start this program by first deciding what methods we will need (apart from main), and what the signatures of those methods will be. This is an important step (especially during the exam) because it will prevent an unnecessary amount of erasing later on. From the problem stated above, we realise we need 4 methods. The first is to decode the message, and this one will have to be passed the secret message and the two char arrays. It will be returning the decoded message as a String. The second method is to take every other character, and combine them into a new String, which will be returned. It needs to be passed the String to perform this on, and we will be passing it an integer value. (The reason for this will be mentioned later on) The third method is to check the string produced by every even character to see if it's a palindrome. This will be passed the string to be checked, and will return a boolean. The fourth and last method is to check the string produced by every odd character to make sure it starts with the words "top secret". It too will be passed the string to check and the string containing the key to look for (the words "top secret"), and return a boolean.


Now that we've decided that, let's get to programming. First, I will make three calls from within main to get started. Note the integer value in the last two method calls. That's because in the "everyOther" method I use modulus to check for either odd or even numbered characters. You'll see the code for this in a bit, but it allows us to re-use a method for performing similar operations.

 String result = decode(secretMessage, array1, array2);
	String palindrome = everyOther(result,0);
	String message = everyOther(result,1); 


Now we should code in our check for a palindrome with a simple if-else statement. The else should print out an error message, and will look something like this,

 if(checkPalindrome(palindrome))
	{
	}
	else
		System.out.println("There was no palindrome.  This message is a fake!"); 


And within the "if" part, we will need to check the string made from all the odd numbered characters for the "top secret" string. If there is no match, we print out an error message. It it is a match, we will print out what the mission instruction is. (making sure we use substring to remove the "top secret" part out of the message) This gives us the following.

 if(checkSecrecy(message, start))
	{
		System.out.print("Your secret mission is: ");
		System.out.println(message.substring(start.length()+1,message.length()));
	}
	else
		System.out.println("There was no \"top secret\".  This message is a fake!"); 


And that is it for our main method. Now we will write code for our first method, the "decode" method. As mentioned before, it is passed a String and two char arrays, and returns a String. Within that method we'll declare and initialise our return variable right aways. Now we have:

 public static String decode(String message, char [] array1, char [] array2)
	{
		String result = "";

		return result;
	} 


When coding, I always make sure to include the return statement as well, but you won't always be able to do this when writing an exam. Now for decoding. We will be using two for loops. The outside loop is for iterating through every character in the string we need to decode, the inside loop is for iterating through every character in the second char array (secret code array). As for the decoding, we will be comparing the character in the string to characters in the second char array, and when we find a match, we take the subscript ("j") and take the character at that spot from the first array (english language array). We then append this character to our return string. This gives us:

 for(int i = 0; i < message.length(); i++)
	{
		for(int j = 0; j < array2.length; j++)
		{
			if(message.charAt(i) == array2[j])
				result += array1[j];
		}
	} 


And our decoding is done. Now for getting every other character out of this string. We decided earlier that we will pass it a string and an integer, and will be returning a String. So our method will look like this: (including return variable and return statement)

 public static String everyOther(String str, int num)
	{
		String result = "";

		return result;
	} 


Now we'll use a for loop for iterating through the string. As I'm sure you've encountered before already, when checking for even or odd numbers, using modulus (%) is easiest. And that's also where that integer we passed in is being used. We'll check for odd or even by "modding" i by 2, and comparring it to the passed integer. If i is equal to 0, it's even, otherwise, it's odd. We'll build our string accordingly, and return it. Here is an example of the loop with if statement.

 for(int i = 0; i < str.length(); i++)
	{
		if(i % 2 == num)
			result += str.charAt(i);
	} 


Now for checking the palindrome. The method just needs a string, and will pass back a boolean variable. We'll initialise the boolean variable to "true", since we will change it to "false" if at any point we notice the string is not a palindrome. We'll also write in the for loop right aways as well. The length of the loop is a bit different, since we just need to check half of the string. (The last half should be the same as the first half, only in reverse) So after cutting the length in half, our method so far will look like:

 public static boolean checkPalindrome(String str)
	{
		boolean result = true;

		for(int i = 0; i < str.length() / 2; i++)
		{
		}

		return result;
	} 


We'll check each character at position i against each character at position str.length() - i - 1. We have to subtract 1 because just using str.length() - i will give us an error message. (It goes past the length of the string since we start counting from 0) If those two characters don't match, we change our return boolean to "false".

 if(str.charAt(i) != str.charAt(str.length() - 1 - i))
		result = false; 


For the last method, we need to check for "top secret". We need to pass this method both the string to check in (the message), and the string to look for ("top secret"). This method will be returning a boolean. We'll initialise our return boolean to "false", since we'll be turning it to "true" if the message contains the word we're looking for. You may have noticed that our boolean initialisations are not the same. One must give consideration as to what to initialise a boolean to. In practise, a developer wants to "switch" a boolean as little as possible in code. While it doesn't affect the computer or how it handles your program, it makes for more readable code, and gives it a cleaner look. (In the case of this method, I opted to go from "false" to "true" so I could avoid using the "!" symbol at the beginning of a long if check)

 public static boolean checkSecrecy(String message, String start)
	{
		boolean result = false;

		return result;      
	} 


And the actual check itself is quite simple. We'll be using substring again to pull out the beginning of the message, of a length equal to the second strings length. Then we check the two against each other, and change our return variable to "true" if they match.

 if(message.substring(0,start.length()).equals(start))
		result = true; 


Our program is now complete. I will leave it to you to write the program and discover what the secret message is. (Trust me, there is one) Otherwise, you can also copy and paste the following program if you're really anxious to perform the secret task.

Also, for those curious, here is the palindrome used. I had to remove the spaces so checking it in the program would be easier.

"Are we not drawn onward, we few, drawn onward to new era?"



Code

Solution Code

Back to the Program-A-Day homepage