I'm using java. I'm trying pull out the last letter of a word of 8 characters or less. Then pulling out each character after
lengthOfWord = word.length();
lc = word.charAt(lengthOfWord -1);
if (lengthOfWord == 1)
System.out.println(lc);
When I try to use a word with one character, it says "String index out of range: -1" and when I try using a word of two characters, it says build successfully, but doesn't print anything.
lengthOfWord
is past the bounds of word
. Use:
lc = word.charAt(lengthOfWord - 1);
Remember that .length() returns the number of characters of an object, but the index of an object starts at 0
and ends at length()-1
.
UPDATE Try this to check all characters in the word:
for (int i = 0; i < word.length(); i++) {
System.out.println("Char " + i + ": " + word.charAt(i));
}
lengthOfWord基于0,因此您可能想尝试lc = word.charAt(lengthOfWord-1);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.