目录
一、分支
1.if的三种结构
1)if语句
public class IfDemo1 {
public static void main(String[] args) {
test1();
}
public static void test1() {
//需求:判断一个数是否是偶数
int a = 5;
if (a % 2 == 0) {
System.out.println("偶数"); //当判断结果为true时执行
}
System.out.println("奇数"); //不管if判断结果如何都会执行
}
}
2)if…else
public class IfDemo1 {
public static void main(String[] args) {
test1();
}
public static void test1() {
//需求:判断一个数是否是偶数
int a = 5;
if (a % 2 == 0) {
System.out.println("偶数"); //当判断结果为true时执行
}else {
System.out.println("奇数"); //当判断结果为false时执行
}
}
}
3)if…else if …else
public class IfDemo1 {
public static void main(String[] args) {
test2();
}
//判断输入的得分属于ABCD中的不同等级
public static void test2() {
Scanner sc = new Scanner(System.in);
System.out.println("请输入您的得分:");
int score = sc.nextInt();
if (score >= 90 && score <= 100) {
System.out.println("A"); //当判断结果为true时执行
}else if (score >= 80 && score < 90) {
System.out.println("B"); //当判断结果为true时执行
}else if (score >= 60 && score < 80) {
System.out.println("C"); //当判断结果为true时执行
}else if (score >= 0 && score < 60) {
System.out.println("D"); //当判断结果为true时执行
}else {
System.out.println("输入的得分有误"); //当判断结果为false时执行
}
}
}
4)案列
public class IfDemo2 {
public static void main(String[] args) {
test1();
}
//通过if判断红绿灯不同状态下车辆如何行驶
public static void test1() {
boolean isRed = false; //红灯关闭
boolean isGreen = true; //绿灯开启
boolean isYellow = false; //黄灯关闭
if (isRed) {
System.out.println("红灯停");
} else if (isGreen) {
System.out.println("绿灯行");
} else if (isYellow) {
System.out.println("黄灯等");
}else
System.out.println("红绿灯状态异常"); //3个灯灯都关闭
}
}
2.switch的使用
1)语句
import java.util.Scanner;
public class SwitchDemo1 {
public static void main(String[] args) {
test1();
}
//理解switch的使用方式,根据输入的性别来推荐一款手机
public static void test1() {
//获取用户输入的性别
System.out.println("请输入性别:");
Scanner sc = new Scanner(System.in);
String sex = sc.next();
switch (sex) {
case "男":
System.out.println("推荐华为手机");
break;
case "女":
System.out.println("推荐苹果手机");
break;
default:
System.out.println("请输入正确的性别");
}
}
}
结论:
注意事项:
switch分支结构的几点注意事项
① 表达式类型只能是byte、short、int、char,JDK5开始支持枚举,JDK7开始支持string、不支持double、float、long
② case给出的值不允许重复,且只能是字面量,不能是变量
③ 正常使用switch的时候,不要忘记写break,否则会出现穿透现象
2)switch穿透性
当case中的执行内容未以break;结束时,会自动执行下一个case中的内容,直到遇到break;结束
public static void main(String[] args) {
test2();
}
//理解switch穿透性
public static void test2() {
int a = 10;
switch (a) {
case 10:
System.out.println("a等于10"); //输出,但无break;结束,继续执行下个case中的内容
case 20:
System.out.println("a等于20"); //同步输出,switch穿透性,未写break时默认穿透到下一个case
break;
case 30:
System.out.println("a等于30");
break;
default:
System.out.println("没有匹配的");
}
}
利用穿透性,简化重复代码(当不同case中的执行内容一致时,可以合理利用穿透性简化代码)
import java.util.Scanner;
public class SwitchDemo1 {
public static void main(String[] args) {
test3();
}
public static void test3() {
//获取周一至周日内的值输出要干的事,事情存在重复,利用switch穿透性简化代码
Scanner sc = new Scanner(System.in);
System.out.println("请输入日期:");
int day = sc.nextInt();
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5:
System.out.println("今天要上班"); //case执行结果一致时,输入1-4,直接穿透到case 5输出结果
break;
case 6:
case 7:
System.out.println("今天要休息"); //case执行结果一致时,输入6,直接穿透到case 7输出结果
break;
default:
System.out.println("输入的日期有误");
}
}
}
二、循环
1.for
1)语句
public class ForDemo1 {
public static void main(String[] args) {
test1();
}
//理解for循环
public static void test1() {
//循环打印三次"hello world"
for (int i = 0; i < 3; i++){
System.out.println("hello world");
}
}
}
执行逻辑:
①循环一开始,执行inti=0一次次
②此时 i=0 ,接着计算机执行循环条件语句:0<3返回true就进到循环体中执行,输出:hello world,然后执行迭代语句i++
③此时 i=1,接着计算机执行循环条件语句:1<3返回true就进到循环体中执行,输出:helloWorld,然后执行迭代语i++
④此时 i=2,接着计算机执行循环条件语句:2<3返回true就进到循环体中执行,输出:helloWorld,然后执行选代语i++
⑤此时 i=3,然后判断循环条件:3<3返回false,循环立即结束。
2)求1-5的和
public static void main(String[] args) {
System.out.println(getSum());
}
public static int getSum() {
int sum = 0;
for (int i = 1; i <= 5; i++) {
sum += i;
}
return sum;
}
3)求1-10的奇数和
public static void main(String[] args) {
System.out.println(getSum());
}
//求1-10的奇数和
public static int getSum() {
int sum = 0;
for (int i = 1; i <= 10; i++) { //或使用i +=2,则无需if求余数
if (i % 2 == 1) { //先取出1 3 5 7 9 再进行累加
sum += i;
}
}
return sum;
}
4)求100-999的水仙花数
public static void main(String[] args) {
getNum();
}
//求100-999的水仙花数
public static void getNum() {
for (int i = 100; i <= 999; i++) {
//获取个位
int ge = i % 10;
//获取十位
int shi = i / 10 % 10;
//获取百位,int类型会直接舍弃小数保留整数
int bai = i / 100;
if (ge * ge * ge + shi * shi * shi + bai * bai * bai == i) {
System.out.println(i);
}
}
}
2.while
与for功能完全一样,for能解决的while也能解决,反之亦然。使用区别:预先知道循环几次时使用for,不确定循环次数时使用while
1)语句
public class WhileDemo {
public static void main(String[] args) {
test1();
}
// 理解while语句与for的区别
public static void test1() {
int i = 0;
while (i < 3) {
System.out.println("hello world");
i++;
}
}
}
2)案例(不知道循环次数时使用while)
需求1:本金100万,存银行年利率3.5%,多少年能翻倍?(多少年即是“不知道的循环次数”)
public static void main(String[] args) {
System.out.println("需要" + test2() + "年后翻倍");
}
//100万本金年利率3.5%,使用while计算多少年翻倍
public static int test2() {
double money = 1000000; //定义初始金额
int year = 0; //定义不知道的循环次数
while (money < 2000000) { //本金小于翻倍金额则继续进入循环
money = money * (1 + 0.035); //每次进入循环增加一年利息
year++; //每次进入循环(每计算一次利息)加一年
}
return year;
}
需求2:珠峰高8848米,一张纸厚0.1毫米,折多少次可以超过珠峰的高度?(多少次即是“不知道的循环次数”)
public static void main(String[] args) {
System.out.println("折叠了" + test3() + "次");
}
public static int test3() {
//珠峰高度8848米转换为毫米
double m = 8848*1000;
//纸张初始厚度为0.1mm
double mm = 0.1;
//初始折叠次数
int count = 0;
while(mm < m){
mm = mm * 2;
count++;
}
return count;
}
}
3.do…while
1)语句
public static void main(String[] args) {
test3();
}
//用dowhile打印3次hello world
public static void test3() {
int i = 0;
do {
System.out.println("hello world");
i++;
} while (i < 3); //若改为while(false),照样会输出一次hello world(先执行再判断)
}
2)案例
与while的区别:while先判断,再执行。do…while是先执行一次do的内容,再与while条件进行判断
import java.util.Scanner;
public class WhileDemo {
public static void main(String[] args) {
test4();
}
//按登录验证密码的方式理解dowhile语句,失败3次则验证结束
public static void test4() {
int count = 0;
do {
System.out.println("请输入密码:");
String pwd = new Scanner(System.in).next();
if (pwd.equals("123456")) {
System.out.println("登录成功");
return;
} else {
System.out.println("密码错误");
count++;
}
} while (count < 3);
System.out.println("登录失败");
}
}
总结:
4.死循环的3种写法
while:
public static void main(String[] args) {
test1();
}
public static void test1() {
while (true) {
System.out.println("hello world");
}
}
for:
public static void main(String[] args) {
test1();
}
public static void test1() {
for (;;) {
System.out.println("hello world2");
}
}
do…while:
public static void main(String[] args) {
test1();
}
public static void test1() {
do {
System.out.println("hello world3");
}
while (true);
}
5.循环嵌套
需求1:打印一个4行x5列的*号组成的图形
public static void main(String[] args) {
printTest();
}
public static void printTest() {
for (int i = 0; i < 4; i++) {
//循环一次结束打印5行*
for (int j = 0; j < 5; j++) {
System.out.print("*"); //去掉ln后打印结果为*****,不再换行
}
System.out.println(); //换行,准备下一次循环输出5个*
}
}
需求2:打印99乘法表
public static void main(String[] args) {
print99();
}
public static void print99() {
//打印99乘法表
int i = 1;
while (i <= 9) {
int j = 1;
while (j <= i) {
System.out.print(i + "*" + j + "=" + i * j + "\t");
j++;
}
System.out.println();
i++;
}
}
6.break和continue的区别
break:跳出并结束当前所执行的循环
continue:跳出当前执行循环的当次执行,进入循环的下一次执行
public class BreakAndContiue {
public static void main(String[] args) {
test1();
test2();
}
//体现break和continue的区别
public static void test1() {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
break;
}
System.out.println(i); //输出结果:1 2 (相当于上班离职了,第3天开始不会再来了)
}
}
public static void test2() {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
System.out.println(i); //输出结果:1 2 4 5(相当于上班请假了,第3天不来但第4天还会来)
}
}
}
7.综合案列
需求1:设计1个简单计算器,支持加减乘除和取余,输入2个数字和1个运算符进行计算
import java.util.Scanner;
public class CalcApp {
public static void main(String[] args) {
//创建Scanner对象
Scanner sc = new Scanner(System.in);
System.out.println("请输入数字1:");
int a = sc.nextInt();
System.out.println("请输入数字2:");
int b = sc.nextInt();
System.out.println("请输入运算符( + - * / % ):");
char op = sc.next().charAt(0);
switch (op) {
case '+':
System.out.println(a + b);
break;
case '-':
System.out.println(a - b);
break;
case '*':
System.out.println(a * b);
break;
case '/':
if (b == 0) {
System.out.println("除数不能为0");
return;
}else System.out.println(a / b);
break;
case '%':
System.out.println(a % b);
break;
default:
System.out.println("输入的运算符有误");
}
}
}
需求2:生成一个1-100的随机整数,猜大小,猜对为止(对两种随机数生成方式的理解)
import java.util.Random;
import java.util.Scanner;
public class GuessNum {
public static void main(String[] args) {
guessNum();
}
//定义方法,实现猜数字游戏
public static void guessNum() {
//方法一:生成1-100的随机数,Math.random()会生成0-1(不包含1)的随机小数,*100会生成0-99的随机数,+1即可生成1-100的随机小数
//int number = (int)(Math.random() * 100 + 1);
//方法二:创建Random对象
Random rd = new Random();
//生成1-100的随机数,参数100表示生成0-99的随机数,+1即可生成1-100的随机数
int number = rd.nextInt(100) + 1;
//创建变量,保存用户输入的数字
Scanner sc = new Scanner(System.in);
//定义死循环,猜数字游戏
while (true) {
System.out.println("请输入数字:");
int num = sc.nextInt();
if (num > number) {
System.out.println("猜大了");
} else if (num == number) {
System.out.println("猜对了");
break;
} else {
System.out.println("猜小了");
}
}
}
}
需求3:生成指定位数的验证码,验证码中每位可以是数字、小写字母和大写字母
public class RandomNum {
public static void main(String[] args) {
//需求:根据指定的数字生成对应位数的验证码,包含数字和大小写字母
System.out.println(getRandomCode(4));
System.out.println(getRandomCode(6));
}
//定义方法,生成随机验证码
public static String getRandomCode(int n) {
// 初始化一个空字符串,用于拼接生成的随机数字
String code = "";
// 根据方法入参,循环n次,生成n位随机数字
for (int i = 0; i < n; i++) {
//随机一个0或1或2代表数字、大写字母、小写字母
int index = (int) (Math.random() * 3);
switch (index) {
case 0:
// 随机生成0到9之间的数字
int num = (int) (Math.random() * 10);
// 将生成的数字拼接到验证码字符串中
code += num;
break;
case 1:
// 随机生成0到25之间的数字,然后将数字加上A对应的ASCII码的数字65,再将ASCII码转为大写字母
char upper = (char) (Math.random() * 26 + 'A');
// 将生成的大写字母拼接到验证码字符串中
code += upper;
break;
case 2:
// 随机生成0到25之间的数字,然后将数字加上a对应的ASCII码的数字97,再将ASCII码转为小写字母
char lower = (char) (Math.random() * 26 + 'a');
// 将生成的小写字母拼接到验证码字符串中
code += lower;
break;
}
}
return code;
}
}
需求4:输出100-200内的素数
public static void main(String[] args) {
getSuNum(100, 200);
}
//定义方法,用于接收判断素数的范围,并返回素数
public static void getSuNum(int start, int end) {
//循环判断入参的范围
for (int i = start; i <= end; i++) {
//循环判断是否是素数
boolean flag = true;
//当i能被2到i-1之间的数字整除时,i不是素数
for (int j = 2; j < i; j++) {
if (i % j == 0) {
flag = false;
break;
}
}
if (flag) { //当flag为true时,输出结果为素数
System.out.print(i+"\t");
}
}
}
三、数组
1.一维数组
1)静态初始化数组
需求:随机点名
public class ArrayTest {
public static void main(String[] args) {
//定义一个包含10个姓名的数组(静态初始化数组)
String[] names = {"张三", "李四", "王五", "赵六", "孙七", "周八", "吴九", "郑十", "王十一", "王十二"};
printRandomName(names);
}
//定义方法,用于打印数组中的随机名字
public static void printRandomName(String[] names) {
//生成0到9之间的随机数
int index = (int) (Math.random() * 10);
//打印随机索引对应的名字
System.out.println(names[index]);
}
}
2)动态初始化数组
需求:录入8个分数,输出最高分、最低分、和平均分
import java.util.Scanner;
public class ArrayTest2 {
public static void main(String[] args) {
getScore();
}
//定义方法,用于接收8个分数,并输出平均分、最高分、最低分
public static void getScore() {
//初始化动态数组,接收8个元素
int[] scores = new int[8];
//创建Scanner对象
Scanner sc = new Scanner(System.in);
//接收输入的分数并存入数组
for (int i = 0; i < scores.length; i++) {
System.out.println("请输入第" + (i + 1) + "个分数:");
scores[i] = sc.nextInt();
}
//计算平均分
int sum = 0;
for (int i = 0; i < scores.length; i++) {
sum += scores[i];
}
double avg = sum / (double) scores.length;
System.out.println("平均分:" + avg);
//获取最高分
int max = scores[0];
for (int i = 1; i < scores.length; i++) {
if (scores[i] > max) {
max = scores[i];
}
}
System.out.println("最高分:" + max);
//获取最低分
int min = scores[0];
for (int i = 1; i < scores.length; i++) {
if (scores[i] < min) {
min = scores[i];
}
}
System.out.println("最低分:" + min);
}
}
区别:静态初始化在知道元素具体值的情况下使用,动态初始化在不知道元素具体值但知道元素总数的情况下使用
3)案例
需求:创建并存储54张扑克牌,并实现洗牌功能
public class ArrayTest3 {
public static void main(String[] args) {
getPoker();
}
//定义方法,实现创建54张扑克牌和洗牌功能并打印
public static void getPoker() {
//初始化数组,存储每张牌的花色
String[] colors = {"♦", "♣", "♥", "♠"};
//初始化数组,存储每张牌的牌面
String[] numbers = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K","A"};
//初始化数组,存储每张牌的索引
String[] pokers = new String[54];
//创建变量,记录第一张牌的索引
int index = 0;
//创建牌,按花色和牌面进行拼接
for (int i = 0; i < numbers.length; i++) {
for (int j = 0; j < 4; j++) {
pokers[index] = colors[j] + numbers[i];
index++;
}
}
//创建大小王
pokers[index++] = "小王";
pokers[index] = "大王";
//打印牌
for (int i = 0; i < pokers.length; i++) {
System.out.print(pokers[i] + " ");
}
System.out.println();
//洗牌
for (int i = 0; i < pokers.length; i++) {
//生成随机索引
int j = (int)(Math.random() * pokers.length);
//创建临时变量,保存当前索引位置的牌
String temp = pokers[i];
//将随机索引位置的牌,赋给当前索引位置
pokers[i] = pokers[j];
//将当前索引位置的牌,赋给随机索引位置
pokers[j] = temp;
}
//打印洗牌结果
for (int i = 0; i < pokers.length; i++) {
System.out.print(pokers[i] + " ");
}
}
}
2.二维数组
1)用法示例
public class ArrayTest4 {
public static void main(String[] args) {
//示例:动态初始化二维数组,代表可以存储3行5列的元素
int[][] array = new int[3][5];
//调用方法使用功能
printArray();
}
//定义方法,理解二维数组
public static void printArray() {
//静态初始化二维数组
int[][] array = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
//按行索引与列索引打印数组元素
//获取行索引长度控制循环次数
for (int i = 0; i < array.length; i++) {
//获取当前行对应的列索引(一维数组)长度控制循环次数 i=0 1 2
for (int j = 0; j < array[i].length; j++) { //j=0 1 2
System.out.print(array[i][j] + "\t");
//打印结果:1 2 3 4 5 6 7 8 9
}
}
//换行
System.out.println();
//通过行索引与列索引获取数组元素
System.out.println(array[0][2]);//打印结果:3
System.out.println(array[1][1]);//打印结果:5
//改变数组元素
array[2][0] = 11;
System.out.println(array[2][0]);//打印结果:11
//获取二维数组长度
System.out.println(array.length); //打印结果:3
//获取二维数组中某一行(一维数组)的长度
System.out.println(array[0].length); //打印结果:3
//通过行索引给新的一维数组赋值
int[] array1 = array[2];
//打印一维数组元素
for (int i = 0; i < array1.length; i++) {
System.out.print(array1[i] + "\t");
//打印结果:11 8 9
}
//换行
System.out.println();
}
}
2)案例
需求:创建二维数字,再将行和列的数据打乱(数字华容道)
public class ArrayTest5 {
public static void main(String[] args) {
//需求:数字华容道
printArray();
}
//定义方法,实现功能
public static void printArray() {
//动态初始化4X4的二维数组
int[][] arr = new int[4][4];
//定义初始变量,用于二维数组赋值
int num = 1;
//循环填充二维数组
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = num;
num++;
}
}
//打印二维数组
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + "\t");
}
//换行
System.out.println();
}
System.out.println("--------------------------------");
//打乱数组元素的顺序
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
int index = (int)(Math.random() * arr.length);
//定义临时变量,保存当前元素
int temp = arr[i][j];
//将index行元素赋给当前元素
arr[i][j] = arr[index][j];
//将临时变量赋给index行元素
arr[index][j] = temp;
}
}
//打印打乱后的数组
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + "\t");
}
//换行
System.out.println();
}
}
}