一、while循环
实例:
public class Test{ public static void main(String[] args){ int i = 1; while(i<30){ System.out.println(i); i++; } } }
二、do-while循环
public class Test{ public static void main(String[] args){ int i = 1; do{ System.out.println(i); i++; } while(i<30); //do-while循环,先执行一次,然后在判断,如果条件成立,在循环执行,如果不成立,继续往下执行 } }
do-while实例(猜数字游戏):
import java.util.*; public class Test{ public static void main(String[] args){ Scanner in = new Scanner(System.in); Random ra = new Random(); int r = ra.nextInt(10); int j; System.out.println("=======猜数字游戏======="); do{ System.out.println("请输入要猜数字(0-9):"); int num = in.nextInt(); if(num<r){ System.out.println("小了"); j = 1; } else if(num>r){ System.out.println("大了"); j = 2; } else{ System.out.println("猜对"); j = 11; } } while(j!=11); } }
三、for循环
public class Test{ public static void main(String[] args){ for(int i=1;i<30;i++){ System.out.println(i); } } }
时间: 2024-10-13 01:51:57