我不知道为什么这段代码没有将'm'的所有实例转换为'M',将'M'的实例转换为'm'。例如,它应该转换为:
Report 98-17, Faculty of Technical matheMatics and InforMatics,%:m 2:M 1:
转换为:
Report 98-17, Faculty of Technical MatheMatics and InforMatics,%:m 2:M1:
感谢。
public static int numberOccurances(String l, char f){
int count=0;
for(int x=0; x<l.length();x++){
if(l.charAt(x)==f)
count++;
}
return count;
}
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
File file = new File("Old.txt");
Scanner scanner = new Scanner(file);
PrintWriter writer = new PrintWriter("New.txt", "UTF-8");
while(scanner.hasNextLine()){
String line = scanner.nextLine();
int numberm=numberOccurances(line, 'm');
int numberM = numberOccurances(line, 'M');
for(int y=0; y<line.length(); y++){
if(line.charAt(y)=='M'){
line=line.substring(0,y) + 'm' + line.substring(y+1);
}
if(line.charAt(y)=='m'){
line=line.substring(0,y) + 'M' + line.substring(y+1);
}
}
if(numberm>0&&numberM>0)
line=line + "%:m " + numberm + ":M" + numberM + ":";
if(numberm>0&&numberM==0)
line=line + "%:m " + numberm + ":";
if(numberM>0&&numberm==0)
line=line + "%:M " + numberM + ":";
writer.println(line);
}
writer.close();
}
答案 0 :(得分:4)
因为您没有使用else
,所以当您将M
修改为m
时,第二个if
会检测m
并反转效果
所以修改
if(line.charAt(y)=='M'){
line=line.substring(0,y) + 'm' + line.substring(y+1);
}
if(line.charAt(y)=='m'){//pay attention to this line
line=line.substring(0,y) + 'M' + line.substring(y+1);
}
到
if(line.charAt(y)=='M'){
line=line.substring(0,y) + 'm' + line.substring(y+1);
}
else if(line.charAt(y)=='m'){//pay attention to this line
line=line.substring(0,y) + 'M' + line.substring(y+1);
}
但是我会推荐一个正则表达式来做这类事情。它使生活更轻松,并将提高性能。