Shakun Bhalla
Shakun Bhalla

Reputation: 15

Output equal null

I've been trying to create a program but I'm struggling because of an error that is causing Null to be output.

  • Problem statement : You have been given a secret mission where you must break the enemy's code. You have already figured out that they encode messages using the following method. Each letter between 'a' and 'z', inclusive, is assigned a distinct two-digit number between 01 and 26, inclusive. A message is encoded by simply replacing each letter with its assigned number. For example, if 't' is assigned 20, 'e' is assigned 05 and 's' is assigned 19, then the message "test" is encoded as "20051920". All original messages contain only lowercase letters. Given assignment of numbers to letters and the encoded message, you need to figure out the original message.
    • Input: First line will contain an integer T = number of test cases. Each test case will contain two lines. First line will contain a string of 26 characters containing the assignment of numbers to letters. The first letter of this string is assigned 01, the second is assigned 02 and so on. Next line will contain encoded message.
    • Output: For each test case, decode and print the original message.

Sample Input and Output

2

abcdefghijklmnopqrstuvwxyz

20051920

faxmswrpnqdbygcthuvkojizle

02170308060416192402

Upvotes: 0

Views: 156

Answers (1)

YoungHobbit
YoungHobbit

Reputation: 13402

You don't need to store the information in map. As we know that it will always be 26 characters, so can store them in a char array and access them directly by indexes. Next you know that each char is represented by two char digit, so fetch the sub strings and convert them to number and access the char array directly. I have used StringBuilder here to store the output.

Here is my implementation of the problem:

public class SecretCode {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int t = scanner.nextInt();
    while (t>0) {
      t--;
      char chars[] = scanner.next().toCharArray();
      String msg = scanner.next();
      StringBuilder builder = new StringBuilder();
      for (int i=0; i<msg.length();) {
        String number = msg.substring(i, i+2);
        Integer num = Integer.parseInt(number);
        builder.append(chars[num-1]);
        i = i+2;
      }
      System.out.println(builder.toString());
    }
  }
}

Upvotes: 1

Related Questions