一、分支结构
1. if 结构
1)单 if 结构
2)if ··· else ···
3)if ··· else if ··· else ···
例:
int a = 10;
if(a>10){
a--;
} else if (a == 10) {
a *= 2;
}else {
a++;
}
2. switch结构
例:
import java.util.Scanner;
public class JAVA {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int date = sc.nextInt();
switch (date) {
case 1:
System.out.println("今天是周一");
break;
case 2:
System.out.println("今天是周二");
break;
case 3:
System.out.println("今天是周三");
break;
case 4:
System.out.println("今天是周四");
break;
case 5:
System.out.println("今天是周五");
break;
case 6:
System.out.println("今天是周六");
break;
case 7:
System.out.println("今天是周日");
break;
default:
System.out.println("劝你别乱说");
}
}
}
注意事项:
1)switch 语句所判断的表达式类型只能是byte,short,int,char,枚举,String
2)case 给出的值不允许出现重复,而且只能是字面量,不能为变量
3)正常使用 switch 语句时,要注意 break 的使用,要避免穿透
二、循环结构
1. for 循环
例:
for(int i = 0;i < 4;i++)
{
System.out.println("Hello World");
}
2. while 循环
例:先判断后执行
int i = 0;
while(i<5)
{
System.out.println(i);
i++;
}
3. do ··· while ···循环
例:先执行后判断
int i = 0;
do
{
System.out.println(i);
i++;
}while(i<5);
4.死循环
for(;;)
{
System.out.println("Hello World");
}
while(true)
{
System.out.println("Hello World");
}
do
{
System.out.println("Hello World");
}while(true);
注意:所有循环的判断条件必须为布尔型
5.循环嵌套
例:执行了25次
for(int i = 0;i<5;i++)
{
for(int j = 0;j<5;j++)
{
System.out.println(j);
}
}
其他类型循环同理
6. break 和 continue
break:直接跳出并结束当前所在循环的执行,也可以结束 case 语句的执行
continue:跳出当前循环的当次执行,直接进入下次执行
三、随机数的生成
//导入Random包
import java.util.Random;
public class JAVA {
public static void main(String[] args) {
//创建r对象
Random r = new Random();
//调用r对象的功能,伪随机生成了范围在0 ~ 10-1的数
int num = r.nextInt(10);
System.out.println(num);
}
}
例:猜数字游戏
import java.util.Random;
import java.util.Scanner;
public class JAVA {
public static void main(String[] args) {
Random r = new Random();
Scanner sc = new Scanner(System.in);
int num = r.nextInt(100);
while(true)
{
int data = sc.nextInt();
if(data > num)
{
System.out.println("猜的太大了,再试一次吧");
}
else if (data < num)
{
System.out.println("猜的太小了,再试一次吧");
}
else
{
System.out.println("恭喜你,猜对了");
break;
}
}
}
}