2015-06-26 77 views
3

我想知道是否有使用toUpperCase的方法來處理StringBuilder?下面是我的代碼,我試圖讓用戶輸入一個短語並將它變成一個首字母縮寫詞。有人通過暗示StringBuilder幫助我,但我無法弄清楚是否有辦法使首字母縮寫爲大寫。任何幫助是極大的讚賞。將stringBuilder強制爲大寫

public class ThreeLetterAcronym { 

public static void main(String[] args) { 
    String threeWords; 
    int count = 0; 
    int MAX = 3; 
    char c; 
    //create stringbuilder 
    StringBuilder acronym = new StringBuilder(); 

    Scanner scan = new Scanner(System.in); 

    //get user input for phrase 
    System.out.println("Enter your three words: "); 
    threeWords = scan.nextLine(); 

    //create an array to split phrase into seperate words. 
    String[] threeWordsArray = threeWords.split(" "); 

    //loop through user input and grab first char of each word. 
    for(String word : threeWordsArray) { 
     if(count < MAX) { 
      acronym.append(word.substring(0, 1)); 
      ++count; 

     }//end if 
    }//end for 

    System.out.println("The acronym of the three words you entered is: " + acronym); 
    }//end main 
}//end class 
+0

答案取決於你什麼時候想把它轉換成大寫... – MadProgrammer

回答

6

大寫字符串就追加到它:

acronym.append(word.substring(0, 1).toUpperCase()) 

或正從StringBuilder的字符串時把字符串爲大寫:

System.out.println("The acronym of the three words you entered is: " + acronym.toString().toUpperCase()); 
+0

這很完美!謝謝伊蘭!我其實嘗試過,但我把.toUpperCase放在了錯誤的地方。我感謝你的幫助,你們都搖滾! – NoobCoderChick

0

您只需將大寫的字符串StringBuilder的。

//loop through user input and grab first char of each word. 
for(String word : threeWordsArray) { 
    if(count < MAX) { 
     acronym.append(word.substring(0, 1).toUpperCase()); 
     ++count; 
    }//end if 
}//end for 

或大寫字符串時,從StringBuilder中獲取它。

System.out.println("The acronym of the three words you entered is: " + acronym.toString().toUpperCase()); 

如果你需要一個圖書館看看阿帕奇公共朗WordUtilsWordUtils.capitalize(str)