I'm doing a practice problem where I have to decipher a certain string by moving each letter back two places in the alphabet, I also need to wrap it around if letter is the first or second letter of the alphabet. It works ok except when the letter is in the first or second position, it seems to decipher letter and print which is great though does it an additional time which is peculiar, I've been trying for many hours and still can't figure out small bug.
Here is my code:
import java.util.ArrayList; public class CCipher{ public static void main(String[]args){ System.out.println(decode("ABC", 1)); } public static String decode(String cipherText, int shift){ String[] alphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","X","Y","Z"}; ArrayList<String>cText = new ArrayList<String>(); String returnString = ""; //seperate individual letters and add them to arrayList for(int i = 0;i<cipherText.length();i++){ cText.add(cipherText.substring(i,i+1)); } //loop through no. of shifts needed for(int i=0;i<shift;i++){ //loop through arrayList for(String cTEXT: cText){ //loop through alphabet for(int j=0;j<alphabet.length;j++){ if(cTEXT.equals(alphabet[j])){ if(j<1){ cTEXT = alphabet[alphabet.length-2]; returnString += cTEXT; }else if(j<2){ cTEXT = alphabet[alphabet.length-1]; returnString += cTEXT; }else if(j>=2){ cTEXT = alphabet[j-2]; returnString += cTEXT; } } } } } return returnString; } }
--- Update ---
Sorry for not giving an example. e.g.If I input "CCC" I get "AAA" output which is great, though if I input "ACC" I get "YVAA" as output, the "Y" is a good thing though I can' understand why from "Y" it is shifted a further two places.