for 语句
for ( 初始语句; 循环体条件表达式; 循环体后语句 ) {
for 循环体
}
- 让程序在满足某条件时,重复执行某个代码块。for 是java中的关键字
- for 语句语法和简单的示例程
- 初始语句在 for 循环开始前执行一次,以后不再执行;循环体条件表达式在每次循环体执行前会执行,如果为 true,则执行循环体,否则循环结束;循环体后语句会在每次循环执行后被执行;
简化输出连续26个字符的程序
使用 for 简化输出连续26个字符的程序
char ch = 'A';
int startNum = ch;
for (int i = 0; i < 26; i++) {
int newNum = startNum + i;
System.out.println(newNum + "\t" + ((char) newNum));
}
简化并增强找整除数的程序
- 简化和增强找整除数的程序
- 使用for语句让程序简洁
- 增加新功能,输出最多10个可以整除的数条件布尔表达式可以用 for 语句外部的变量
- 循环体执行后的语句可以有多个表达式,用逗号分开
int divided = 100;
int divisor = 3;
int found = 0;
for (int i = 0; i < 100 && found < 10; i++) {
if (divided % divisor == 0) {
System.out.println(divided + "可以整除" + divisor + "。商为" + divided / divisor);
found++;
}
divided++;
}
break 语句
结束循环
break 语句可以结束循环
在求整除程序中使用break提前结束循环
int dividend = 100;
int divisor = 3;
int foundCount = 0;
int toBeFound = 5;
for (int i = 0; i < 100; i++) {
if (dividend % divisor == 0) {
System.out.println(dividend + "可以整除" + divisor + "。商为" + dividend / divisor);
foundCount++;
}
dividend++;
if (foundCount >= toBeFound) {
break;
}
}
System.out.println("总共找到" + foundCount + "个可以整除" + divisor + "的数。");
continue 语句
跳过不符合条件的循环
继续语句可以结束当次循环的执行,开始下一次循环体的执行
int dividend = 10;
int divisor = 21;
int foundCount = 0;
int toBeFound = 5;
for (int i = 0; i < 200; i++, dividend++) {
if (divisor > dividend) {
System.out.println("跳过" + dividend + ", 因为它比除数" + divisor + "小。");
continue;
}
if (dividend % divisor == 0) {
System.out.println(dividend + "可以整除" + divisor + "。商为" + dividend / divisor);
foundCount++;
}
if (foundCount >= toBeFound) {
break;
}
}
System.out.println("总共找到" + foundCount + "个可以整除" + divisor + "的数。");