返回三个大写字母的最后一个字母

时间:2016-11-28 01:25:37

标签: java string

我正在尝试返回三个用户输入字符串的最后一个字母并将其大写。

例如,如果我的字符串是"运行","沙发"和"计算机"我的输出应该是" NAR"。

public static String lastLetters(String word1, String word2, String word3){

    // I tried to capitalize all the words first and input them into a string
    String x = word1.toUpperCase(); 
    String y = word2.toUpperCase();
    String z = word3.toUpperCase();

    word1 =  x.substring(x.lastIndexOf(' ') + 1);
    word2 =  y.substring(y.lastIndexOf(' ') + 1);
    word3 =  z.substring(z.lastIndexOf(' ') + 1);
    String lastLetters = (word1, word2, word3); 
    return lastLetters;
}
}
//The output should be
System.out.println("The last letters of the words forms the word: " + lastLetters(word1,word2,word3));

1 个答案:

答案 0 :(得分:0)

考虑这个答案

public static void main(String[] args) throws Exception {

    String word1 = "run";
    String word2 = "sofa";
    String word3 = "computer";

    System.out.println(lastLetters (word1, word2, word3));

}

private static String lastLetters(String word1, String word2,
        String word3) {

    return (word1.substring(word1.length() -1) + 
            word2.substring(word2.length() -1) + 
            word3.substring(word3.length() -1)).toUpperCase();
}