The Captain Crunch decoder ring works by taking each letter in a string and adding 13 to it. For example, 'a' becomes 'n' and 'b' becomes 'o'. The letters "wrap around" at the end, so 'z' becomes 'm'.
this is what i've gotten after editing it a bit from peoples comments, but now it keeps telling me that output may have not been initialized and i have no clue why... also is there anything else i need to fix in my program?
in this case, i am only concerned with encoding lowercase characters
public class captainCrunch {
public static void main (String[] Args) {
Scanner sc = new Scanner(System.in);
String input;
System.out.print("getting input");
System.out.println("please enter word: ");
input = sc.next();
System.out.print(" ");
System.out.print("posting output");
System.out.print("encoding" + input + " results in: " + encode(input));
}//end of main
/*
*
*/
public static String encode(String input){
System.out.print(input.length());
int length = input.length();
int index;
String output;
char c;
String temp = " ";
for (index = 0; index < length; index++) {
c = input.charAt(index);
if(c >= 'a' && c <= 'm'){
c += 13;
}else if(c >= 'n' && c <= 'z'){
c -= 13;
}
output = temp + (char)(c);
}
return output;
}
}
It is because you have no value of output if the length of the for loop is 0. So if length == 0 then output will never have been set when you try and return it.
Fix it by doing:
Additionally you you are only setting output to one string, you need to append to it each time around the loop, not set it to an entirely new value:
Really you would be better off using a
StringBuilder
for this though.For this sort of thing StringBuilder is a LOT more efficient than a String (since String are immutable new ones have to be made for every concatenation).