在格式化字符串输入时遇到问题
问题描述:
我试图获取用户输入的输入以转为小写,然后将第一个字符输入为大写。例如,如果我为我的第一个输入输入一个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();
}
}
答
在Java中,字符串是不可变的(不能改变),所以像substring
和toLowerCase
方法产生新的字符串 - 他们不修改现有的字符串。
因此,而不是:
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);
答
类似@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);