Java学习笔记15

do-while循环时while循环的变体
语法如下:
do{
  // 循环体
 语句(组);
}while(循环继续条件);

如果循环中的语句至少需要执行一次,那么建议使用do-while循环.

for循环
常用以下的通用形式编写循环:
i = initialValue;  // 初始化循环控制变量
while(i < endValue){
 // Loop body
 ...
 i++;  // 修改循环控制变量
}
可以用for循环简化以上的循环:
for(i = initialValue; i < endValue; i++){
  // Loop body
  ...
}

使用for循环打印Welcome to Java!100次
for(int i = 0; i < 100; i++){
 System.out.println("Welcome to Java!");
}

注意:如果省略for循环中的循环继续条件,则隐含地认为循环继续条件为true.
for( ; ; ){
  // Do something
}

等价于:
for( ; true; ){
 // Do something
}

等价于:
while(true){
 // Do something
}

采用哪种循环:
1)若已知重复次数,就采用for循环
2)若无法确定重复次数,则采用while循环
3)若至少执行一次,则用do-while循环替代while循环.

 

package welcome;

import java.util.Scanner;

/*
 * 如果循环中的语句至少需要执行一次,那么建议使用do-while循环
 */
public class TestDoWhile {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int sum = 0;
        int data;
        
        do{
            System.out.print("输入一个整数,若输入0程序将退出: ");
            data = in.nextInt();
            
            sum += data;
        }while(data != 0);
        
        System.out.println("The sum is " + sum);
    }
}

 

posted @ 2016-12-25 16:58  xiaorong1115  阅读(135)  评论(0编辑  收藏  举报