深刻理解If-else语句

来源:互联网 发布:录制夜听用的软件 编辑:程序博客网 时间:2024/06/08 18:37

If-else

今天在写程序时遇到了一个问题,题目是:编写一个程序,输出一个字符串中大写字母,小写字母,以及非字母的个数。下面是我开始写的程序。

package com.wangjing.SortMethod;public class StringExercise{    public static void main(String[] args) {        String s="asdghkbnr_}*$SGVFJHTVNO";        char[] c=new char[s.length()];  //把字符串转换成字符数组        int upperCase=0;        int lowerCase=0;        int other=0;        s.getChars(0, s.length(), c, 0);        for(int i=0;i<s.length();i++){            if(c[i]>=65 && c[i]<=90){  //if(c[i]>'A' && c[i]<'Z')                upperCase++;            }                                  if(c[i]>=97 && c[i]<=122){                lowerCase++;            }else{                other++;            }        }        System.out.print("大写字母:"+upperCase);        System.out.print("小写字母:"+lowerCase);        System.out.print("其他非字母:"+other);    }/*output:大写字母:10小写字母:9其他非字母:14*/

很奇怪,明明只有4个非字母,却输出了14个。又检查了程序,尝试在for循环的第二个if语句前加了else,结果正确,4个。原来程序在运行时,当字符串中没有大写字母时,就会继续执行第二个if语句;当执行第二个if语句时,遇到了前九个小写字母,程序跳出到下一次循环;但是,当字符串中出现大写字母时,应该是跳出循环的,由于我误把else if写成了if(原来理解不透彻。),导致程序进入到第二个if语句,判断不是小写字母了,当时是other++了。。

总结

一个完整的句子是:

if(){}else if(){}     //这是一句
if(){}if(){           //这是两句}else{}

所以下次写if语句时,要遵循正确格式:

if(){}if(){}else{}           //这样是不是就不容易混淆了
0 0
原创粉丝点击