2016-11-28 164 views
0

我想返回三個用戶輸入字符串的最後一個字母並將其大寫。返回三個字符串的最後一個字母大寫

例如,如果我的字符串是「運行」,「沙發」和「電腦」,我的輸出應該是「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)); 
+0

爲什麼你得到一個空間的最後一個索引?如果字符串的長度小於3,會發生什麼情況?爲什麼不打印出你的方法中的值?你怎麼看'String lastLetters =(word1,word2,word3);'是嗎? –

+0

認爲最後一個索引會給我我的字符串的最後一個字母。對於字符串lastLetters,由於我在word1,word2,word3中存儲了新的「單詞」,我認爲這些值會存儲在其中?這兩個錯誤都是錯誤的 –

+0

。考慮子字符串,但使用字符串的長度減1也許。 –

回答

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(); 
} 
相關問題