【问题标题】:Output last letter of a string输出字符串的最后一个字母
【发布时间】: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

标签: java string


【解决方案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 

尝试结合你的两个答案。但也请注意您帖子中关于从长度中减一的评论。

【讨论】:

    【解决方案2】:
    System.out.println("last character: " +
                           string.substring(string.length() - 1)); 
    

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 2015-12-26
      • 1970-01-01
      • 2022-07-06
      • 1970-01-01
      • 2011-07-28
      • 1970-01-01
      • 1970-01-01
      • 2019-01-23
      • 2018-07-21
      相关资源
      最近更新 更多