为何大小写切换代码中独立if语句失效,else if语句可正常运行?
大小写切换程序中独立if与else if的逻辑差异问题
问题核心原因是两个独立if会对同一个字符进行两次判断修改,而else if是互斥判断,只会执行其中一个分支。
具体执行流程拆解:
拿小写字符'e'举例:
- 第一个
if判断'e'属于小写范围,执行ch-32转成大写'E'; - 紧接着第二个
if判断刚转换后的'E'属于大写范围,又执行ch+32转回小写'e'。
拿大写字符'W'举例:
- 第一个
if不成立,直接跳过; - 第二个
if判断'W'属于大写范围,转成小写'w'——这一步逻辑是对的,但小写字符会被来回转换,最终所有字母都变成小写。
改用else if后,只要第一个条件成立(小写转大写),第二个else if就不会再执行;如果第一个条件不成立(不是小写),才会判断第二个条件(大写转小写),这样每个字符只会被转换一次,逻辑完全正确。
可正常运行的代码:
public class ToggleCase { public static void main(String args[]) { String s = "We ArE THe BeSt", s1 = ""; int i; for(i=0; i<s.length(); i++) { char ch = s.charAt(i); if(ch >= 'a' && ch <= 'z') ch= (char)(ch-32); else if(ch >= 'A' && ch <= 'Z') ch= (char)(ch+32); // main statement s1 += ch; } System.out.println("Toggle case: "+s1); } }
无法正常运行的代码:
public class ToggleCase { public static void main(String args[]) { String s = "We ArE THe BeSt", s1 = ""; int i; for(i=0; i<s.length(); i++) { char ch = s.charAt(i); if(ch >= 'a' && ch <= 'z') ch= (char)(ch-32); if(ch >= 'A' && ch <= 'Z') ch= (char)(ch+32); //change is here s1 += ch; } System.out.println("Toggle case: "+s1); } }
内容的提问来源于stack exchange,提问作者Ajinkya Kamble
相关产品推荐
相关产品推荐

