英文:
Why if statement is not working in the code, while else if statement works?
问题
Working code (工作代码):
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); // 主要语句
s1 += ch;
}
System.out.println("Toggle case: "+s1);
}
}
Non-working code (不工作的代码):
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); // 更改在这里
s1 += ch;
}
System.out.println("Toggle case: "+s1);
}
}
英文:
I am working on strings for a while.
I have a code of toggle case, i.e. a program to convert lower case to upper and vice versa. I'm getting a problem with the condition checking. If I don't use else if, I am getting all lower case and when I use else if, i get my program working correctly. please see whats wrong. Thank you in advance.
Working code:
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);
}
}
Non-working code:
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);
}
}
答案1
得分: 1
让我们假设你当前的字符是'a',即字符值为97。在你的非工作代码中,第一个 'if' 语句匹配到了这个字符,所以你减去了32。现在,ch 的值变成了65。这代表字符 'A'。
所以第二个 'if' 语句再次匹配,将字符值恢复到了97。
英文:
Let's say your current character is 'a', that is the character value 97. In your non-working code the first 'if' statement matches the char, so you subtract 32. Now ch has the value of 65. This represents the character 'A'.
So the second 'if' statement matches again and raises the character value back to 97.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论