有人可以帮助我在初学者编程课程中,我无法让我的程序输出字符串的最后一个字母吗?这是我的计划:
public class String {
private static java.lang.String string;
public static void main(java.lang.String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a string: "); //user enters a word
java.lang.String word = input.nextLine();
System.out.print("The length of " + word + " is " +
word.length()); //gives the number of characters in the word
java.lang.String length = input.nextLine();
System.out.print("The first character: " + word.charAt(0)); //gives the first letter of word
java.lang.String first = input.next();
System.out.print("The last character: " + word.charAt(4)); //gives the last letter of word
java.lang.String last = input.next();
}
}
答案 0 :(得分:1)
你知道如何获得这个词的长度,你在这里做到了:
System.out.print("The length of " + word + " is " + word.length());
但是当你试图获取最后一个字母而不是使用该信息时,你使用常量“4”:
System.out.print("The last character: " + word.charAt(4)); //gives the last letter of word
尝试将两个答案结合起来。但请注意你的帖子中有关从长度中减去一个的评论。
答案 1 :(得分:0)
System.out.println("last character: " +
string.substring(string.length() - 1));
希望它有所帮助!