循环
1.for循环(重点)
for ( ; ; ) {
}
for循环的优势:
1. for之后的小括号内容,可读性更强
2. 可以通过for之后小括号,里面的内容大概推算出整个循环会执行多少次
3. for循环和一些特殊的数据关系非常紧密
使用案例
class Demo1 {
public static void main ( String[ ] args) {
for ( int i = 1 ; i <= 100 ; i += 1 ) {
System. out. println ( i) ;
}
}
}
class Demo3 {
public static void main ( String[ ] args) {
for ( char ch = 'A' ; ch <= 'Z' ; ch += 1 ) {
System. out. println ( ch) ;
}
}
}
2.break【重点】
字面含义:
跳出,打破
代码中的功能是跳出循环结构或者switch case结构
break关键字可以在循环过程中,当前循环结果出现了预期的内容,终止循环。
使用案例
class Demo4 {
public static void main ( String[ ] args) {
int i = 1 ;
while ( i <= 100 ) {
System. out. println ( i) ;
if ( 50 == i) {
System. out. println ( "循环跳出!!!" ) ;
break ;
}
i += 1 ;
}
}
}
3.continue[了解]
continue关键字
结束当前循环,进入下一次循环
ps注意事项
for循环应多加联系,在使用时应想好思维逻辑。
break注意插入的地方不然可能达不到预期效果。
小白在编写代码时应养成代码格式正确工整,且注释不能忘。
5.练习题
class HomeWork1 {
public static void main ( String[ ] args) {
for ( int i = 1 ; i <= 9 ; i++ ) {
for ( int j = 1 ; j <= i; j++ ) {
System. out. print ( i + "*" + j + "=" + ( i * j) + " " ) ;
}
System. out. println ( ) ;
}
}
}
import java. util. Scanner;
class HomeWork2 {
public static void main ( String[ ] args) {
int num = 0 ;
Scanner sc = new Scanner ( System. in) ;
System. out. println ( "请输入一个正整数:" ) ;
num = sc. nextInt ( ) ;
for ( int i = 2 ; i <= num; i++ ) {
if ( num % i == 0 ) {
System. out. println ( "i : " + i) ;
num /= i;
i-- ;
}
}
}
}
class HomeWork3 {
public static void main ( String[ ] args) {
int num1 = 1 ;
int num2 = 1 ;
System. out. println ( "1 1 " ) ;
for ( int i = 1 ; i <= 28 ; i++ ) {
int temp = num1;
num1 = num2;
num2 += temp;
System. out. print ( num2 + " " ) ;
}
}
}
class HomeWork4 {
public static void main ( String[ ] args) {
double ret = 1 ;
for ( int i = 2 ; i <= 15 ; i++ ) {
ret *= i;
}
System. out. println ( "ret : " + ret) ;
}
}
class HomeWork5 {
public static void main ( String[ ] args) {
for ( int i = 1 ; i <= 100 ; i++ ) {
if ( i % 7 == 0 || i % 10 == 7 || i / 10 == 7 ) {
System. out. println ( "过" ) ;
continue ;
}
System. out. println ( i) ;
}
}
}