What's the problem with this code in Secret Messages? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

What's the problem with this code in Secret Messages?

import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner sc=new Scanner(System.in); String str=sc.nextLine(); String str1=str.toLowerCase(); String s1="abcdefghijklmnopqrstuvwxyz"; String s2="zyxwvutsrqponmlkjihgfedcba"; String[]arr1=s1.split(""); String[]arr2=s2.split(""); for(int i=0;i<arr1.length-1;i++){ str1=str1.replaceAll(arr1[i],arr2[i]); } System.out.println(str1); } }

26th Sep 2022, 7:08 AM
Killiam Chances
Killiam Chances - avatar
2 Answers
+ 1
The problem is you will switch b for y, and then you will switch y to b, but the previous b is no more a b... Example: abcz -> zycz-> zbxz -> zbcz -> abca Your input is not going to be abca but zbcz because you do your loop <arr1.length-1 so you will skip the last position (the z) (Edit) One solution could be: loop only to half of the arr1 replaceAll(arr1[i], '*'); replaceAll(arr2[i],arr1[i]); replaceAll('*',arr2[i]);
26th Sep 2022, 7:44 AM
Tomás Ribeiro
Tomás Ribeiro - avatar
0
Input : aaa => zzz => aaa result
26th Sep 2022, 8:24 AM
Jayakrishna 🇮🇳