I created this code that looks at a string token and formats it so that every character is moved along by one. The characters are all lowercase and from a to z.
So if my input is
abcz
Output is
bcda
Right now I added all the alphabets to an arraylist, and the code determines the index of each character and adds one to it. If it finds z, it prints a so that index of the arraylist is not out of range.
List<String> letters = new ArrayList<String>();
String alp = "abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i<26; i++)
{
letters.add(Character.toString(alp.charAt(i)));
}
String token = sc.next();
for (int i = 0; i<token.length(); i++)
{
if (letters.get(letters.indexOf(Character.toString(token.charAt(i)))).equals("z"))
{
System.out.print("a");
}
else
{
System.out.print(letters.get(letters.indexOf(Character.toString(token.charAt(i)))+1));
}
}
A simple loop with a bit of modular arithmetic will do, why bother with so many objects?
We increase the offset from
'a'by one, and take the remainder modulo 26 to get an offset in the range from 0 to 25.