(1)多次重复做相同的事情(有一定的规律)
(2)简化代码(写更少的代码做更多的事情)
2,循环条件
3,修改循环变量的值,使其朝着循环结束的方向走。
4 , 循环体
先判断后执行的循环
while(循环条件){
循环操作
}
注意事项:
(1)循环条件不能永假。
(2)循环变量的修改,一定要朝循环结束的方向进行。
(3)尽量避免带new的代码出现在循环中。
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//循环变量
String input="y";
while(input.equals("y")){
System.out.println("请输入矩形的宽:");
double width = sc.nextDouble();
System.out.println("请输入矩形的高:");
double height = sc.nextDouble();
double area = width * height;
System.out.println("矩形的宽为" + width + "高为" + height + "面积是" + area);
System.out.println("是否继续?(y/n)");
//接受用户是否继续
input=sc.next();
}
System.out.println("88,欢迎下次光临!");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int i=0;//循环变量
int total=0;//保存和
while(i<=100){
total+=i;
i++;
}
System.out.println("和为:"+total);
}
public static void main(String[] args) {
int year=2006;
double student=8;
while(student<20){
student=student*(1+0.25);
year++;
}
System.out.println("到"+year+"培训学员人数将达到20万人!");
}
先执行后判断的循环
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String input="";
do{
System.out.println("是否继续(y/n)?");
input=sc.next();
}while(input.equals("y"));
System.out.println("程序退出!");
}
public static void main(String[] args) {
int she=0,count=0;//摄氏温度 计数器
double hua=0;//华氏温度
System.out.println("摄氏温度\t华氏温度");
do {
hua= she * 9 / 5.0 + 32;
System.out.println(she+"\t"+hua);
she+=20;
count++;
} while (she<=250&&count<10);
}
1,while有可能一次都不执行,do-while至少执行一次
2,While为先判断后执行,而do-while是先执行后判断
3,这两种循环是可以相互替代的
4,多用于循环次数不确定情况下
循环次数确定的情况下,for循环比while和do-while结构更加简洁、明了。
执行:1-2-3-4-2-3-4-2-3-4....
1,参数初始化允许多个表达式(逗号隔开)
2,条件判断可以使用多个逻辑表达式(&& || !)
3,更新循环变量也是运行多个表达式(逗号隔开)
使用举例:
for (int i = num, j=0; i >= 0; i--,j++) {
System.out.println(j+"+"+i+"="+(i+j));
}
特殊的for循环:
for(;;){
System.out.println("这是死循环");
}
while(){
...
....
break; //跳出整个循环 break通常在循环中与条件语句一起使用
...
..
}
/**
*实现
* for(){
switch(){
while/if(){
break;
}
}
}
*
*/
public class Demo3 {
?
public static void main(String[] args) {
// TODO Auto-generated method stub
for (int i = 0; i < 3; i++) {
switch(i){
case 0:
System.out.println("000000000000");
while(i<4){
break;
}
case 1:
System.out.println("11111111111");
break;
case 2:
System.out.println("2222222222222");
break;
default:
System.out.println("33333333333");
}
}
}
?
}
案例1:
/**
* 求1~100的偶数和
* @author Administrator
*
*/
public class Demo4 {
public static void main(String[] args) {
int sum=0;
for(int i=1;i<=100;i++){
if(i%2!=0){
continue;
}
sum+=i;
}
System.out.println(sum);
}
}
案例2:
public static void main(String[] args) {
// TODO Auto-generated method stub
for (int i = 0; i < 3; i++) {
switch(i){
case 0:
System.out.println("000000000000");
while(i<4){
i++;
continue;
}
case 1:
System.out.println("11111111111");
break;
case 2:
System.out.println("2222222222222");
break;
default:
System.out.println("33333333333");
}
}
}
1,不确定次数使用while循环
(1) While循环:先判断后执行
(2) Do-while循环:先执行后判断
原文:https://www.cnblogs.com/xtzhiker/p/14866242.html