2015-03-02 62 views
0

我試圖獲取用戶輸入的輸入以轉爲小寫,然後將第一個字符輸入爲大寫。例如,如果我爲我的第一個輸入輸入一個RseNAL,我想格式化輸入,以便將「Arsenal」放入data.txt文件中,我也想知道是否有辦法將每個第一個字符放在上面,例如,如果一個團隊有多個詞,即。 mAN uNiTeD格式化爲曼聯以寫入文件。在格式化字符串輸入時遇到問題

我下面的代碼是我嘗試過的,我無法讓它工作。任何意見或幫助,將不勝感激。

import java.io.*; 
import javax.swing.*; 
public class write 
{ 
    public static void main(String[] args) throws IOException 
    { 
     FileWriter aFileWriter = new FileWriter("data.txt"); 
     PrintWriter out = new PrintWriter(aFileWriter); 
     String team = ""; 
     for(int i = 1; i <= 5; i++) 
     { 
      boolean isTeam = true; 
      while(isTeam) 
      { 
       team = JOptionPane.showInputDialog(null, "Enter a team: "); 
       if(team == null || team.equals("")) 
        JOptionPane.showMessageDialog(null, "Please enter a team."); 
       else 
        isTeam = false; 
      } 
      team.toLowerCase();     //Put everything to lower-case. 
      team.substring(0,1).toUpperCase(); //Put the first character to upper-case. 
      out.println(i + "," + team); 
     } 
     out.close(); 
     aFileWriter.close(); 
    } 
} 

回答

0

在Java中,字符串是不可變的(不能改變),所以像substringtoLowerCase方法產生新的字符串 - 他們不修改現有的字符串。

因此,而不是:

team.toLowerCase();     
team.substring(0,1).toUpperCase(); 
out.println(team); 

你會需要像:

String first = team.substring(0,1).toUpperCase(); 
String rest = team.substring(1,team.length()).toLowerCase();     
out.println(first + rest); 
0

類似@DNA建議,但會拋出異常,如果字符串的長度爲1所以增加了支票相同。

 String output = team.substring(0,1).toUpperCase(); 
     // if team length is >1 then only put 2nd part 
     if (team.length()>1) { 
      output = output+ team.substring(1,team.length()).toLowerCase(); 
     } 
     out.println(i + "," + output);