简体   繁体   English

为什么不打印单词的最后一个字符?

[英]Why doesn't this print the last character of the word?

I'm using java. 我正在使用Java。 I'm trying pull out the last letter of a word of 8 characters or less. 我正在尝试取出8个字符以内的单词的最后一个字母。 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. 当我尝试使用一个字符的单词时,它说“字符串索引超出范围:-1”,当我尝试使用两个字符的单词时,它说“ build”成功,但是不打印任何内容。

lengthOfWord is past the bounds of word . lengthOfWord超出了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 . 请记住,.length()返回对象的字符数,但是对象的索引从0开始,以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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM