output will become 901-13015-11-1-25 since, I = 9 space = 0 A = 1 M = 13 space = 0 O = 15 K = 11 A = 1 Y = 25
I don't think you read the assignment properly.
That would mean that: AA
becomes 11
. And K
... also becomes 11
. Not sure this is what you wanted.
switch (fs) {
case "A":
assuming it's all consecutive, with "A" becoming 1, and "Z" becoming 26: characters are just numbers (their unicode value), and those letters are in sequence. So, instead of a gigantic switch block, all you need is:
int num = fs.charAt(0) - 'A' + 1;
this will turn "A" into 1, and "Z" into 26.
As the comments already said, your problem is that fs
isn't just "A"
. It's "Hello"
. You need to loop through the characters. As space gets special treatment (turning into 0), and presumably anything that isn't "A" - "Z" should crash:
for (char c : fs.toCharArray()) {
int num = charToCode(c);
}
and then write charToCode:
public int charToCode(char c) throws IllegalArgumentException {
if (c == ' ') return 0;
if (c >= 'A' && c <= 'Z') return c - 'A' + 1;
throw new IllegalArgumentException(
"Only spaces and capital letters allowed");
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…