执行顺序
顺序结构
自上而下执行
分支结构
根据条件,选择对应的代码执行
if
switch
循环结构
控制某段代码重复执行
for
while
do-while
死循环
Public class DIE {
public static void main(String[] args) {
//for
//for (; ;){
//System.out.println("helloworld1");
//}
//while
//while (true){
// System.out.println("helloworld2");
//}
//do-while
do {
System.out.println("helloworld3");
}while (true);
}
}
循环嵌套
外部循环每循环一次,内部循环会全部执行完一轮
public class xunhuan {
public static void main(String[] args) {
//每次打印五句我爱你,打印三天
for (int i = 1;i <= 3;i++){
for (int j = 1;j <= 5;j++){
System.out.println("我爱你"+ " 第"+i+"天");
}
System.out.println("----------");
}
}
}
for (int i = 1;i <= 3;i++){
for (int j = 1;j<=20;j++){
System.out.print("*");//不换行
}
System.out.println();//换行
}
跳转关键字
break
跳出并结束当前所在循环的执行
只能用于结束所在循环或者结束所在switch分支的执行
public class Break {
//说五句我爱你,第三句停止
public static void main(String[] args) {
for (int i = 1;i <= 5;i++){
System.out.println("我爱你");
if(i == 3){
break;
}
}
}
}
continue
用于跳出当前循环的当此执行,直接进入循环的下一次执行
只能在循环中使用
public class Continue {
//五天我爱你,第三天可以不说,第四天继续
public static void main(String[] args) {
for (int i = 1;i <= 5;i++){
if(i == 3){
continue;
}
System.out.println("我爱你"+" 第"+i+"天");
}
}
}
生成随机数
ctrl+alt+t选择循环
nextInt(n)
只能生成0~n-1之间的数,不包括n
random包前不包后
import java.util.Random;
public class RandomDemo {
public static void main(String[] args) {
//掌握生成随机数的步骤
//1、导包
//2、创建一个random对象用于生产随机数
Random r = new Random();
//3、调用random提供的功能得到随机数
for (int i = 1;i <= 20;i++) { //用循环设置出现多少个随机数
int data = r.nextInt(10);//0-9
System.out.println(data);
}
}
}
生成指定区间的随机数
减加法
生成1-10之间的随机数
import java.util.Random;
public class RandomDemo {
public static void main(String[] args) {
//掌握生成随机数的步骤
//1、导包
//2、创建一个random对象用于生产随机数
Random r = new Random();
//3、调用random提供的功能得到随机数
for (int i = 1;i <= 20;i++) { //用循环设置出现多少个随机数
int data2 = r.nextInt(10) + 1;//1-10
System.out.println(data2);
}
}
}
【案例】猜数字游戏
import java.util.Random;
import java.util.Scanner;
public class guessNumber {
public static void main(String[] args) {
Random r = new Random();
int luckyNumber = r.nextInt(1,101);
Scanner sc = new Scanner(System.in);
while (true){
System.out.println("请输入猜测数据:");
int guessNumber = sc.nextInt();
if (guessNumber > luckyNumber){
System.out.println("数据过大");
} else if (guessNumber < luckyNumber) {
System.out.println("数据过小");
} else{
System.out.println("猜中啦");
break;
}
}
}
}