For this task, you will create a program that takes a key as input and uses that key to unscramble a string of randomized characters using pointers. You will first prompt the user to input a key of 20 or fewer characters. Then, the user will input a long string of scrambled characters of no more than 1000 characters. This is the message to be deciphered. To decode the message, the string will be divided into even groups of characters and then organized based on the key. The key will take the form of: 5: 42513 In this case, there are groups of 5 letters in the scrambled message, and the order of groups for the unscrambled message is 12345. In other words, the first group of 5 letters would be the fourth group in the decoded message, the second group of 5 letters would be the second, and so on. For example, the following scrambled message: RETMESASUPSSAGETHISIERSEC will be broken up into 5 different groups (concluded from 5:... and length of message): RETME SASUP SSAGE THISI ERSEC and then organized according to the given key (42513): THISI SASUP ERSEC RETME SSAGE which, adjusting the spaces, gives \"THIS IS A SUPER SECRET MESSAGE\". The number of letters in a group should evenly divide the total number of characters in the scrambled string. Your program should check though that this is actually the case. Additionally, your program has to check if a given group number is valid, e.g. there is no block 7 in the example given above. If there are excess characters, excess groups or ill-defined block numbers, when outputting the final deciphered message, the program should also state that the code may have been altered by enemy spies. You may not use strlen () for this task. It is safe to assume that the block size as well as the group numbers are always less than 10.
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
public class Cipher {
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println(\"Input decoder key: \");
String key = s.next();
int groupSize=0;
String groups=\"\";
Map<Integer,String> map = new TreeMap<Integer,String>();
try{
if(key.contains(\"-\"))
{
groupSize = Integer.parseInt(key.split(\"-\")[0]);
groups = key.split(\"-\")[1];
}
else if(key.contains(\":\"))
{
groupSize = Integer.parseInt(key.split(\":\")[0]);
groups = key.split(\":\")[1];
}
System.out.println(\"Input decoder message: \");
String message = s.next();
if(message.length()%groupSize!=0)
throw new Exception();
int k=0;
for(int i=0;i<message.length();i+=groupSize)
{
map.put(Integer.parseInt(groups.charAt(k++)+\"\"), message.substring(i, groupSize+i));
}
}catch(Exception e)
{
System.out.println(\"Code may have been altered by enemy spies\");
}
for(Map.Entry<Integer, String> entry: map.entrySet())
{
System.out.print(entry.getValue()+\" \");
}
}
}