How do I shift array characters to the right in Java?

二次信任 提交于 2019-12-01 22:33:04

You are using the loop index i instead of the ith character in your loop, which means the output of your code does not depend the input String (well, except for the length of the output, which is the same as the length of the input).

Change

char c = (char) (((i - 'a' + 1) % 26) + 'a');

to

char c = (char) (((ch[i] - 'a' + 1) % 26) + 'a');

Replace i - 'a' + 1 with ch[i] - 'a' + 1

class encoded {

   public static void main(String[] args)
   {
     String s1 = "hello";
     char[] ch = s1.toCharArray();
     for(int i=0;i<ch.length;i++)
     { 
        char c = (char) (((ch[i] - 'a' + 1) % 26) + 'a');
        System.out.print(c);
     }
   }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!