- 基本语法
循环变量初始化;
while(循环条件){
循环体(语句);
循环变量迭代;
}
说明:
1.while循环也有四要素
2.只是四要素放的位置上不一样
while循环流程图
练习题:
1.打印出1-100之间所有能被3整除的数
public class While循环练习1 {
//打印1-100内所有能被3整除的数
public static void main (String[] args) {
int i = 1;
while(i<100) {
if(i % 3 ==0) {
System.out.println(i);
}
i++;
}
}
}
2.打印40-200之间所有的偶数
public class While循环练习2 {
public static void main (String[] args) {
int i= 40;
while(i<=200) {
if(i % 2 ==0) {
System.out.println("i="+i);
}i++;
}
}
}
do -while 循环
-
基本语法
循环变量初始化;
do{
循环体(语句);
循环变量迭代;
}while(循环条件);
do-while先执行,再判断,也就是一定会执行一次。
do-while流程图
练习:
1.输出1-200内可以被5整除但不可以被3整除的数并统计个数
public class DoWhile练习2 {
//输出1-200内可以被5整除但不能被3整除的数,并统计个数
public static void main (String[] args) {
int i = 1;
int count = 0;
do {
if(i%5==0 && i%3!=0 ) {
System.out.println("i="+i);
count++;
}i++;
}while(i<=200);
System.out.println("count="+count);
}
}
2.催债,如果不还钱就一直打到还钱。
import java.util.Scanner;
public class DoWhile循环练习1 {
//催债
public static void main (String[] args) {
Scanner myscanner = new Scanner(System.in);
char answer = ' ';
do {
System.out.println("你使用了头槌!对他造成500伤害");
System.out.println("还不还钱? y /n");
answer = myscanner.next().charAt(0);
System.out.println("它的回答是:"+answer);
}while(answer !='y');
System.out.println("他打不过你,终于还钱了");
}
}