深刻理解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
- 深刻理解If-else语句
- IF-ELSE IF-ELSE语句
- Delphi if else 语句
- if~else 语句再认识
- if else 语句
- JavaScript If...Else 语句
- PHP If...Else 语句
- PHP If...Else 语句
- if-else语句
- JavaScript If...Else 语句
- JavaScript If...Else 语句
- JAVA If-else语句
- if...else... 语句
- sql if else 语句
- if-else语句注意事项
- 010 else -if 语句
- 3.9、if else 语句
- if..else 语句应用
- Android 如何切换到 Transform API?
- 祝大家六时吉祥,万事如意!
- 2、单目相机外参标定(camera_calibration_external)
- B树
- Android批量打包
- 深刻理解If-else语句
- 蓝桥杯 波动数列 (DP&滚动数组 好题)
- Docker教程:docker machine的配置和命令
- Linux设置串口波特率等参数
- 集成百度导航SDK遇到的一些问题。
- 合并顺序表
- C++用new来创建对象和非new来创建对象的区别
- PB TreeView 查找节点(转)
- 安装gdb时遇到的makeinfo找不到的问题