输出字符串的最后一个字母

问题描述:

有人可以帮助我在初学者编程课程,我不能让我的程序输出字符串的最后一个字母?下面是我的程序:输出字符串的最后一个字母

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(); 
    } 
} 
+2

当然,因为你得到的索引4,而不是最后一个字符。要获得最后一个索引,string.length - 1 – Winter

你知道如何让字的长度,你这样做是在这里:

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的评论。

System.out.println("last character: " + 
         string.substring(string.length() - 1)); 

希望它有帮助!