So I'm learning about functions and methods, and trying to create a function that would allow me to replace a Letter with a Number, thus "a" would be 0, "b" would be 1, so on and so forth. I don't know ascii at all, and have only run into creating a very long if, else statement, but I don't even know if I'm on the right track. I'm trying to find a way to create a function without having to make a long conditional statement and use less line of code.
This is the new code I have written with suggestions:
public class CaesarCipher {
/*
* create function that converts a letter to a number
* ex. a -> 0, b -> 1, etc...
*/
static char letterToNumber (char firstLetter){
if (firstLetter < 'a' || firstLetter > 'z') {
}
return firstLetter;
}
static int numberToLetter (int firstNumer){
if (firstNumber < '0' || firstNumber '25'){
}
return firstNumber;
}
public static void main(String[] args) {
char a = 0;
// TODO Auto-generated method stub
System.out.println (letterToNumber (a)); //suppose to compile to convert a -> the number 0
System.out.println(numberToLetter (1)); //compile to convert 1 -> the letter b
}
}
The simplest approach is just to subtract the literal 'a'
... which will implicitly convert both your input letter and the 'a'
to int
:
public int convert(char letter) {
if (letter < 'a' || letter > 'z') {
throw new IllegalArgumentException("Only lower-case ASCII letters are valid");
}
return letter - 'a';
}
The nice thing about this solution is that it's reasonably "obviously correct" (with the assumption that the letters 'a' to 'z' are consecutive in UTF-16). You don't need to include any magic integer values.
See more on this question at Stackoverflow