alphabet. How to do the opposite when there is a number, and you need a letter?
public static void main(String args[]) {
String s = "HUYES";
String t = "";
for (int i = 0; i < s.length(); ++i) {
char ch = s.charAt(i);
if (Character.isLetter(ch)) { // check if the character is a letter
if (!t.isEmpty()) {
t += " ";
}
int n = (int) ch - (int) 'A'; // if you want to check, then add 'A'+ 1. Where the beginning of the alphabet begins with 1
t += String.valueOf(n);
}
}
System.out.println(t);
}
Get ascii code of 'A', add the number and then use the ascii code to convert to char char c = ((int)'A' + num)
^ this can be a source of errors. So make sure you aren't doing something silly
i just need to have a number from 0-25 and convert to alphabetical order and get the letter
I gave you the whole snippet and you're still asking me that o.O
holy moly, that's so ... cryptic. I would never understood what this code is doing without extra description. Why not just do it more straightforward? class EnglishAlphabet { static String alphabet = "abcdefghijklmnopqrstuvwxyz"; int positionInAlphabet(char letter) { return alphabet.indexOf(letter); } Character letterAtPosition(int pos) { if (0 <= pos && pos < alphabet.length()) { return alphabet.charAt(pos); } else { return null; // or throw if you want to be NPE-free } } } More readable. More maintainable - just imagine that some day comes PO and says "Ok, now we need to support Spanish and French".
thanks to you I understood my shortcomings
Обсуждают сегодня