在Java中,条件语句和分支语句的语法规范和其他编程语言大致相同(就本人学习过的编程语言而言,指C和Python),不多赘述。这篇博客主要介绍Java与其他编程语言稍有不同的地方。
(1)for循环新形式:将一个集合作为一个整体放入for循环中,在for循环中可将集合中的元素进行逐个处理, 例:
String[] names = {“Wang”,“Zhang”,“Li”,“Wu”};
for(String option: names) {
System.out.println(option);
}
输出结果为:
(2)在循环条件中不要使用浮点值来比较值是否相等, 否则可能导致不精确的循环次数和结果
double item=1, sum=0;
while(item!=0){
sum+=item;
item-=0.2;
}
System.out.println(sum);
结果没有输出
(3)布尔型与整型之间不能相互转换, 循环与分支条件必须得到一个布尔型的值, 不能像C那样接受整型;
(4)条件操作符?:是if-else的一种紧缩格式表达;
(5)switch整型表达式的值必须是int兼容的类型, 即byte, short,char或int
不论执行哪个分支, 程序都会继续执行直至遇到break语句或到达整个switch语句末尾才结束switch语句
分支语句的示例:
public class SwitchDemo2 {
public static void main(String[] args) {
int month = 2; int year = 2000; int numDays = 0;
switch (month) {
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
numDays = 31; break;
case 4: case 6: case 9: case 11:
numDays = 30; break;
case 2:
if (((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0))
numDays = 29;
else
numDays = 28;
break;
}
System.out.println(“The number of Days = ” + numDays);
}
}
运行结果为:
(6)关于跳转语句:
1loop: while(true){
2 for(. . .){
3 switch(. . .){
4 case -1:
5 case '\n':
6 break loop; //跳出while到11行
7 . . .
8 }
9 }
10 }
11 test: for(. . .){
12 while(. . .){
13 if(. . .){
14 . . .
15 continue test; //跳到11行
16 }
17 }
18}
示例如下(在一个字符串中查找特定子串):
public class BreakAndContinueWithLabel{
public static void main(String[] args){
String searchMe = “Look for a substring in me”;
String substring = “sub”;
boolean found = false;
int max = searchMe.length() - substring.length();
test: for (int i = 0; i <= max; i++) { // i:子串查找开始位置
int n = substring.length();
int j = i; // j:当前在主串中的查找位置
int k = 0; // k:当前在子串中的查找位置
while (n-- != 0) {
if (searchMe.charAt(j++) != substring.charAt(k++)) {
continue test;
}
}
found = true;
break test; // = break;
}
System.out.println(found ? “Found!” : “Didn't find!”);
}
}
运行结果: