【发布时间】:2017-01-26 12:11:29
【问题描述】:
有人可以帮助我在初学者编程课程中,我无法让我的程序输出字符串的最后一个字母吗?这是我的程序:
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();
}
}
【问题讨论】:
-
当然,因为您在索引 4 处获取 char,而不是最后一个。要获取最后一个索引, string.length - 1