Day-3
1.语句(while)
1.1循环结构
代表语句: while , do while, for
while语句格式:
while (条件表达式)
{
执行语句;
}
注:当在控制台进入无限循环,按ctrl+c即可停止
do while语句格式:
do
{
执行语句;
}while(条件表达式);
do while 特点是条件无论是否满足,循环体至少被执行一次.
2.语句(do while)
3.语句(for)
4.语句(for和while的区别)
for (int x = 0; x<3;x++)
{
System.out.println("x="+x);//3 6
}
//在这里离开了大括号,x不存在的,注意(条件表达式)
System.out.println("x====="+x);
int y = 0;
while(y<3)
{
System.out.println("y="+y);
y++;
}
System.out.println("y===="+y);
/*
1.变量有自己的作用域,对于for来讲:如果将用于控制循环的增量定义在for语句中,那么该变量只在for语句内有效,
2,for和while 可以进行呼唤,如果需要定义循环增量,用for更合适
总结:
什么时候试用循环结构?
当要对某些语句执行很多次时,就试用循环结构.
*/
5.语句(循环语句的其它特点)
class ForTest
{
public static void main(String[] arg)
{
int x = 1;
for(System.out.println("a");x<3;System.out.println("c"))
{
System.out.println("d");
x++;
}
//abcdc
}
}
///为了检测语句是怎么执行的,先来什么后做什么
6.语句(for语句练习)
/*1,获取1~10的和,并打印.
2,1~100之间的7的倍数的个数,并打印.*/
class ForTest2
{
public static void main(String[] arg)
{
//1,定义变量用于存储不断变化的和.
int sum = 0;
//2,定义变量,记录住不断变化的被加的数.
int x =1;
//3,定义循环,重复加法的过程,
while(x<=10)
{
sum = sum + x;
x++;
}
System.out.println("sum="+sum);
/*
循环注意:
一定要明确哪些语句需要参与循环,哪些不需要.
0+1
1+2
3+3
6+4
*/
}
}
//用for来提现,
int sum = 0;
for(int x=0; x<=10;x++)
{
sum+=x;
}
System.outprintln("for sum = "+sum);
/*
2,1~100之间的7的倍数的个数,并打印.
思路:
1,先对1~100进行循环(遍历)通过循环的形式
2,在遍历的过程中,定义条件,只对7的倍数进行操作.
3,因为7的倍数不确定