day01
输出你最想说的一句话
编写步骤:
定义类 Homework1
定义 main 方法
控制台输出5行字符串类型常量值
public class Homework1{public static void main(String[] args){System.out.println("猪门永存!");System.out.println("猪门永存!");System.out.println("猪门永存!");System.out.println("猪门永存!");System.out.println("猪门永存!");}
}
按步骤编写代码,效果如图所示
编写步骤:
定义类 Homework2
定义 main 方法
控制台输出5行字符串类型常量值
控制台输出5行字符类型常量值
public class Homework2{public static void main(String[] args){System.out.println("善学如春起之苗");System.out.println("不见其增,日有所长");System.out.println("假学如磨刀之石");System.out.println("不见其损,年有所亏");System.out.println("加油吧!少年");System.out.println('J');System.out.println('A');System.out.println('V');System.out.println('A');System.out.println('!');}
}
按步骤编写代码,效果如图所示
编写步骤:
定义类 Homework3
定义 main 方法
控制台输出所有布尔类型常量值
public class Homework3{public static void main(String[] args){System.out.println(true);System.out.println(false);}
}
按步骤编写代码,效果如图所示
编写步骤:
定义类 Homework4
定义 main 方法
定义2个 byte 类型变量,分别赋 byte 类型范围内最大值和最小值,并输出在控制台
定义2个 short 类型变量,分别赋 short 类型范围内最大值和最小值,并输出在控制台
定义2个 int 类型变量,分别赋 int 类型范围内最大值和最小值,并输出在控制台
定义2个 long 类型变量,分别赋 long 类型范围内最大值和最小值,并输出在控制台
public class Homework4{public static void main(String[] args){byte byteMin = -128, byteMax = 127; //byte:-2^7 ~ 2^7-1short shortMin = -32768, shortMax = 32767; //short:-2^15 ~ 2^15-1int intMin = -2147483648, intMax = 2147483647; //int:-2^31 ~ 2^31-1long longMin = -9223372036854775808L, longMax = 9223372036854775807L; //long:-2^63 ~ 2^63-127System.out.println("byteMin=" + byteMin);System.out.println("byteMax=" + byteMax);System.out.println("shortMin=" + shortMin);System.out.println("shortMax=" + shortMax);System.out.println("intMin=" + intMin);System.out.println("intMax=" + intMax);System.out.println("longMin=" + longMin);System.out.println("longMax=" + longMax);}
}
按步骤编写代码,效果如图所示
编写步骤:
定义类 Homework5
定义 main 方法
定义2个 float 类型变量,分别赋值,并输出在控制台
定义2个 double 类型变量,分别赋值,并输出在控制台
public class Homework5{public static void main(String[] args){float float1 = -3.14F, float2 = 3.14F;double double1 = -3.4, double2 = 3.4;System.out.println("float1=" + float1);System.out.println("float2=" + float1);System.out.println("double1=" + double1);System.out.println("double2=" + double2);}
}
交换两个变量的值
编写步骤:
定义类 Homework6
定义 main 方法
定义两个整数变量 a和b 并赋值
控制台输出变量 a和b 互换前的值
定义有一个第三方变量 temp
利用第三方变量 temp 使 a和b 的值互换
控制台输出变量 a和b 互换后的值
public class Homework6{public static void main(String[] args){int a = 10, b = 20;System.out.println("a=" + a);System.out.println("b=" + b);int temp;temp = a;a = b;b = temp;System.out.println("a=" + a);System.out.println("b=" + b);}
}
按步骤编写代码,效果如图所示
编写步骤:
定义类 Homework7
定义 main 方法
定义2个 int 类型变量 x和y ,x 赋值为100,y 赋值为200
定义新变量 add,保存变量 x和y 的和并打印到控制台
定义新变量 sub,保存变量 x和y 的差并打印到控制台
定义新变量 mul,保存变量 x和y 的积并打印到控制台
定义新变量 div,保存变量 x和y 的商并打印到控制台
public class Homework7{public static void main(String[] args){int x = 100, y = 200;int add, sub, mul, div;add = x + y;sub = x - y;mul = x * y;div = x / y;System.out.println("x,y的和为:" + add);System.out.println("x,y的差为:" + sub);System.out.println("x,y的积为:" + mul);System.out.println("x,y的商为:" + div);}
}
按步骤编写代码,效果如图所示
编写步骤:
定义类 Homework8
定义 main 方法
定义2个 double 类型变量 x和y ,x 赋值为100.8,y 赋值为20.6
定义新变量 add,保存变量 x和y 的和并打印到控制台
定义新变量 sub,保存变量 x和y 的差并打印到控制台
定义新变量 mul,保存变量 x和y 的积并打印到控制台
定义新变量 div,保存变量 x和y 的商并打印到控制台
public class Homework8{public static void main(String[] args){double x = 100.8, y = 20.6;double add, sub, mul, div;add = x + y;sub = x - y;mul = x * y;div = x / y;System.out.println("x,y的和为:" + add);System.out.println("x,y的差为:" + sub);System.out.println("x,y的积为:" + mul);System.out.println("x,y的商为:" + div);}
}
Java的基本数据类型有哪些?String是基本数据类型吗?
byte,short,int,long,float,double,char,boolean
String是引用数据类型
float f = 3.4; 是否正确,表达式 15/2*2 的值是多少
不正确,float f = 3.4f;
15/2*2 = 7*2 = 14
char 型变量中是否可以存储一个汉字
可以
day02
强制类型转换练习
按步骤编写代码,效果如图所示
先声明两个 byte 类型的变量 b1和b2 ,并分别赋值10和20,求 b1和b2 变量的和,并将结果保存在 byte 类型的变量 b3 中,最后输出 b3 变量的值
先声明两个 short 类型的变量 s1和s2 ,并分别赋值1000和2000,求 s1和s2 变量的和,并将结果保存在 short 类型的变量 s3 中,最后输出 s3 变量的值
先声明1个 char 类型的变量 c1 赋值为 'a' ,再声明一个 int 类型的变量 num 赋值为5,求 c1和num 变量的和,并将结果保存在 char 类型的变量 letter 中,最后输出 letter 变量的值
先声明两个 int 类型的变量 i1和i2 ,并分别赋值5和2,求 i1和i2 的商,并将结果保存在 double 类型的变量 result 中,最后输出 result 变量的值,如何得到结果2.5呢
public class Homework1{public static void main(String[] args){byte b1 = 10, b2 = 20, b3;//b3 = b1+b2; //错误: 不兼容的类型,从int转换到byte可能会有损失b3 = (byte)(b1+b2); System.out.println("byte类型的b1和b2的和为:"+b3); //b3=30short s1 = 1000, s2 = 2000, s3; //s3 = s1+s2; //错误: 不兼容的类型,从int转换到short可能会有损失s3 = (short)(s1+s2);System.out.println("short类型的s1和s2的和为:"+s3); //s3=3000char c1 = 'a';int num = 5;char letter;//letter = c1+num; //错误: 不兼容的类型,从int转换到char可能会有损失letter = (char)(c1+num); System.out.println("char类型的c1和int类型的num的和为:"+letter); //letter=fint i1 = 5, i2 = 2;double result;//result = i1/i2; //result=2.0result = (double)i1/i2;System.out.println("int类型的i1和i2的商为:"+result); //result=2.5}
}
按步骤编写代码,效果如图所示
定义两个 int 类型变量 a1和a2 ,分别赋值10和11,判断变量是否为偶数,拼接输出结果
定义两个 int 类型变量 a3和a4 ,分别赋值12和13,判断变量是否为奇数,拼接输出结果
public class Homework2{public static void main(String[] args){int a1 = 10, a2 = 11;boolean result1 = (a1%2==0);System.out.println(a1+"是偶数?"+result1);boolean result2 = (a2%2==0);System.out.println(a2+"是偶数?"+result2);int a3 = 12, a4 = 13;boolean result3 = (a3%2==1);System.out.println(a3+"是奇数?"+result3);boolean result4 = (a4%2==1);System.out.println(a4+"是奇数?"+result4);}
}
计算时间
案例:为抵抗洪水,战士连续作战89小时,编程计算共多少天零多少小时,效果如图所示
定义一个 int 类型变量 hours,赋值为89
定义一个 int 类型变量 day,用来保存89小时中天数的结果
定义一个int类型变量 hour,用来保存89小时中不够一天的剩余小时数的结果
输出结果
public class Homework3{public static void main(String[] args){int hours = 89, day, hour;day = hours/24;hour = hours%24;System.out.println("为抵抗洪水,战士连续作战89小时:");System.out.println(hours+"是"+day+"天"+hour+"小时");}
}
案例:今天是周2,100天以后是周几?
效果如图所示
定义一个 int 类型变量 week,赋值为2
修改 week 的值,在原值基础上加上100
修改 week 的值,在原值基础上模以7
输出结果,在输出结果的时候考虑特殊值,例如周日
public class Homework4{public static void main(String[] args){int week = 2;week += 100;week %= 7;System.out.println("今天是周2,100天以后是周"+(week==0 ? "日":week));}
}
案例:求三个整数 x、y和z 中的最大值
如图所示
定义三个 int 类型变量 x、y和z,x 赋值为3,y 赋值为4,z 赋值为1
定义一个 int 类型变量 max,先存储 x和y 中的最大值(使用三元运算符)
再次对 max 赋值,让它等于上面 max与z 中的最大值(使用三元运算符)
输出结果
public class Homework5{public static void main(String[] args){int x = 3, y = 4, z = 1, max;max = x>y ? x:y;max = max>z ? max:z;System.out.println(x+","+y+","+z+"中的最大值是:"+max);}
}
案例:判断今年是否是闰年
闰年的判断标准是:
1.可以被4整除,但不可被100整除
2.可以被400整除
如图所示:
定义一个 int 类型变量 year,赋值为今年年份值
定义一个 boolean 类型变量,用来保存这个年份是否是闰年的结果
输出结果
public class Homework6{public static void main(String[] args){int year = 2018;boolean result;result = (year%4==0 && year%100!=0) || (year%400 == 0);System.out.println(year+(result ? "是闰年":"不是闰年"));}
}
华氏度转摄氏度
小明要到美国旅游,可是那里的温度是以华氏度为单位记录的。他需要一个程序将华氏温度(80度)转换为摄氏度,并以华氏度和摄氏度为单位分别显示该温度。
定义一个 double 类型变量 hua,存储华氏温度80
定义一个 double 类型变量 she,存储摄氏温度,根据公式求值
输出结果
public class Homework7{public static void main(String[] args){double hua = 80, she;she = (hua-32)/1.8;System.out.println("华氏度"+hua+"F转为摄氏度是"+she+"C");}
}
如下代码的计算结果是
public class Test{public static void main(String[] args){int i = 1;i *= 0.2; i++; System.out.println("i="+i);} }
public class Test{public static void main(String[] args){int i = 1;i *= 0.2; //i=0i++; //i=1System.out.println("i="+i);}
}
如下代码的计算结果是
public class Test{public static void main(String[] args){int j = 2;j *= j+1;int k = 2;k *= ++k;System.out.println("j="+j);System.out.println("k="+k); } }
public class Test{public static void main(String[] args){int j = 2;j *= j+1; // j= j*(j+1) = 2*(2+1) = 6int k = 2;k *= ++k; // k = k*(++k) = 2*(2+1) = 6System.out.println("j="+j); //j=6System.out.println("k="+k); //k=6}
}
如下代码的计算结果是
public class Test{public static void main(String[] args){int a = 3;int b = 1;if(a = b){ System.out.println("Equal");}else{System.out.println("Not Equal");}} }
public class Test{public static void main(String[] args){int a = 3;int b = 1;if(a = b){ //错误: 不兼容的类型,int无法转换为booleanSystem.out.println("Equal"); }else{System.out.println("Not Equal");}}
}
如下代码的计算结果是
public class Test{public static void main(String[] args){int a = 8, b = 3;System.out.println(a>>>b);System.out.println(a>>>b | 2);} }
public class Test{public static void main(String[] args){int a = 8, b = 3;System.out.println(a>>>b); //8: 0000 1000//1:0000 0001//1System.out.println(a>>>b | 2); //1:0000 0001//2:0000 0010//3:0000 0011//3}
}
如何用最有效的方法计算2乘以8
public class Test5{public static void main(String[] args){int a = 2, b;b = a<<3;// 2:0000 0010//16:0001 0000System.out.println(b);}
}
day03
判断5的倍数
从键盘输入一个整数,判断它是否是5的倍数
import java.util.Scanner;
public class Homework1{public static void main(String[] args){Scanner sc = new Scanner(System.in);System.out.println("请输入一个整数:");int num = sc.nextInt();if(num%5 == 0){System.out.println(num+"是5的倍数");}else{System.out.println(num+"不是5的倍数");}}
}
判断字符类型
从键盘输入一个字符,判断它是字母还是数字,还是其他字符
import java.util.Scanner;
public class Homework2{public static void main(String[] args){Scanner sc = new Scanner(System.in);System.out.println("请输入一个字符");char c = sc.next().charAt(0);if(c>='0' && c<='9'){System.out.println(c+"是数字字符");}else if(c>='a' && c<='z' || c>='A' && c<='Z'){System.out.println(c+"是字母字符");}else{System.out.println(c+"是非数字非字母的其他字符");}}
}
计算折扣后金额
从键盘输入订单总价格 totalPrice (总价格必须>=0),根据优惠政策计算打折后的总价格
编写步骤:
判断当 totalPrice>=500,discount 赋值为0.8
判断当 totalPrice>=400且<500时,discount 赋值为0.85
判断当 totalPrice>=300且<400时,discount 赋值为0.9
判断当 totalPrice>=200且<300时,discount 赋值为0.95
判断当 totalPrice>=0且<200时,不打折,即 discount 赋值为1
判断当 totalPrice<0时,显示输入有误
输出结果
import java.util.Scanner;
public class Homework3{public static void main(String[] args){Scanner sc = new Scanner(System.in);System.out.println("请输入订单总价格:");double totalPrice = sc.nextDouble();double discount = 0.0;if(totalPrice < 0){System.out.println("总价格输入有误!");}else{if(totalPrice >= 500){discount = 0.8;}else if(totalPrice >= 400){discount = 0.85;}else if(totalPrice >= 300){discount = 0.9;}else if(totalPrice >= 200){discount = 0.95;}else{discount = 1;}totalPrice *= discount;System.out.println("打折后的总价格:"+totalPrice);} }
}
输出月份对应的英语单词
从键盘输入月份值,输出对应的英语单词
import java.util.Scanner;
public class Homework4{public static void main(String[] args){Scanner sc = new Scanner(System.in);System.out.println("请输入月份值:");int month = sc.nextInt();switch(month){case 1:System.out.println("January");break;case 2:System.out.println("February");break;case 3:System.out.println("March");break;case 4:System.out.println("April");break;case 5:System.out.println("May");break;case 6:System.out.println("June");break;case 7:System.out.println("July");break;case 8:System.out.println("August");break;case 9:System.out.println("September");break;case 10:System.out.println("October");break;case 11:System.out.println("November");break;case 12:System.out.println("December");break; default:System.out.println("月份值输入有误!");break;}}
}
计算今天是星期几
定义变量 week 赋值为上一年12月31日的星期值(可以通过查询日历获取),定义变量 year、month和day,分别赋值今天日期年、月和日,计算今天是星期几
public class Homework5{public static void main(String[] args){int week = 6; //查询日期得知int year = 2023;int month = 5;int day = 30;int days = 0; //用来存储总天数switch(month){case 12:days += 30; //11月的满月天数,这里没有break,继续往下走case 11:days += 31; //10月的满月天数,这里没有break,继续往下走case 10:days += 30; //9月的满月天数,这里没有break,继续往下走case 9:days += 31; //8月的满月天数,这里没有break,继续往下走case 8:days += 31; //7月的满月天数,这里没有break,继续往下走case 7:days += 30; //6月的满月天数,这里没有break,继续往下走case 6:days += 31; //5月的满月天数,这里没有break,继续往下走case 5:days += 30; //4月的满月天数,这里没有break,继续往下走case 4:days += 31; //3月的满月天数,这里没有break,继续往下走case 3:days += 28; //2月的满月天数,这里没有break,继续往下走//闰年多一天if(year%4==0 && year%100!=0 || year%400==0){days++;} case 2:days += 31; //1月 case 1:days += day;break;default:System.out.println("月份输入有误!");break;}week += days;week %= 7;switch(week){case 0:System.out.println("星期日");break;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; default:break; }}
}
判断年、月和日是否合法
从键盘输入年、月和日,要求年份必须是正整数,月份范围是[1,12],日期也必须在本月总天数范围内,如果输入正确,输出”年-月-日“结果,否则提示输入错误
import java.util.Scanner;
public class Homework01{public static void main(String[] args){Scanner sc = new Scanner(System.in);System.out.println("请输入年:");int year = sc.nextInt();System.out.println("请输入月:");int month = sc.nextInt();System.out.println("请输入日:");int day = sc.nextInt();if(year>0){if(month>=1 && month <=12){int days = 0; //用来存储某月的总天数if(month==2){if(year%4==0 && year%100!=0 || year%400==0){days = 29;}else{days = 28;}}else if(month==4 || month==6 || month==9 || month==11){days = 30;}else{days = 31;}if(day>=1 && day <= days){System.out.println(year+"-"+month+"-"+day);}else{System.out.println("日期输入不合法!");}}else{System.out.println("月份输入不合法!");}}else{System.out.println("年份输入不合法!");}}
}
判断打鱼还是晒网
从键盘输入年、月和日,假设从这一年的1月1日开始执行三天打鱼两天晒网,那么你输入的这一天是在打鱼还是晒网
import java.util.Scanner;
public class Homework02{public static void main(String[] args){Scanner sc = new Scanner(System.in);System.out.println("请输入年:");int year = sc.nextInt();System.out.println("请输入月:");int month = sc.nextInt();System.out.println("请输入日:");int day = sc.nextInt();boolean flag = false;if(year>0){if(month>=1 && month <=12){int days = 0; //用来存储某月的总天数if(month==2){if(year%4==0 && year%100!=0 || year%400==0){days = 29;}else{days = 28;}}else if(month==4 || month==6 || month==9 || month==11){days = 30;}else{days = 31;}if(day>=1 && day <= days){flag = true;}else{System.out.println("日期输入不合法!");}}else{System.out.println("月份输入不合法!");}}else{System.out.println("年份输入不合法!");} if(flag){int totalDays = 0; //用来存储总天数switch(month){case 12:totalDays += 30; //11月的满月天数,这里没有break,继续往下走case 11:totalDays += 31; //10月的满月天数,这里没有break,继续往下走case 10:totalDays += 30; //9月的满月天数,这里没有break,继续往下走case 9:totalDays += 31; //8月的满月天数,这里没有break,继续往下走case 8:totalDays += 31; //7月的满月天数,这里没有break,继续往下走case 7:totalDays += 30; //6月的满月天数,这里没有break,继续往下走case 6:totalDays += 31; //5月的满月天数,这里没有break,继续往下走case 5:totalDays += 30; //4月的满月天数,这里没有break,继续往下走case 4:totalDays += 31; //3月的满月天数,这里没有break,继续往下走case 3:totalDays += 28; //2月的满月天数,这里没有break,继续往下走//闰年多一天if(year%4==0 && year%100!=0 || year%400==0){days++;} case 2:totalDays += 31; //1月 case 1:totalDays += day;break;default:break;}String result = (totalDays%5==1 || totalDays%5==2 || totalDays%5==3) ? "打鱼":"晒网";System.out.println(result);}}
}
判断星座
声明变量 month 和 day,用来存储出生的月份和日期,判断属于什么星座,各个星座的日期范围如下
白羊座:3.21~4.19
金牛座:4.20~5.20
双子座:5.21~6.21
巨蟹座:6.22~7.22
狮子座:7.23~8.22
处女座:8.23~9.22
天秤座:9.23~10.23
天蝎座:10.24~11.22
射手座:11.23~12.21
摩羯座:12.22~1.19
水瓶座:1.20~2.18
双鱼座:2.19~3.20
public class Homework03{public static void main(String[] args){int month = 9;int day = 25;if((month==1 && day>=20) || (month==2 && day<=18)){System.out.println("水瓶座");}else if((month==2 && day>=19) || (month==3 && day<=20)){System.out.println("双鱼座");}else if((month==3 && day>=21) || (month==4 && day<=19)){System.out.println("白羊座");}else if((month==4 && day>=20) || (month==5 && day<=20)){System.out.println("金牛座"); }else if((month==5 && day>=21) || (month==6 && day<=21)){System.out.println("双子座");}else if((month==6 && day>=22) || (month==7 && day<=22)){System.out.println("巨蟹座");}else if((month==7 && day>=23) || (month==8 && day<=22)){System.out.println("狮子座");}else if((month==8 && day>=23) || (month==9 && day<=22)){System.out.println("处女座");}else if((month==9 && day>=23) || (month==10 && day<=23)){System.out.println("天秤座");}else if((month==10 && day>=24) || (month==11 && day<=22)){System.out.println("天蝎座");}else if((month==11 && day>=23) || (month==12 && day<=21)){System.out.println("射手座");}else if((month==12 && day>=22) || (month==1 && day<=19)){System.out.println("摩羯座"); }}
}
switch 能否作用在 byte 上,能否作用在 long 上,能否作用在 String 上
能,不能,能
switch支持的类型有 byte、short、int、char、String和枚举
day04
5个一行输出1~100的偶数
public class Homework1{public static void main(String[] args){//方案一:/* int count = 0;//挑出0~100之间的偶数for(int i=2; i<=100; i+=2){count++; //统计偶数的个数if(count<5){ //5个为一行,用逗号隔开System.out.print(i+",");}else{ //超过5个就换行,清空个数System.out.println(i);count = 0; }} *///方案二://挑出0~100之间的偶数for(int i=2; i<=100; i+=2){if(i%10 != 0){ //10个为一行,用逗号隔开System.out.print(i+",");}else{ //超过10个就换行System.out.println(i);}} }
}
趣味折纸
世界最高山峰是珠穆朗玛峰,它的高度是8848.86米,假如我有一张足够大的纸,它的厚度是0.1毫米。请问,我折叠多少次,可以折成珠穆朗玛峰的高度
public class Homework2{public static void main(String[] args){double height = 8848.86*1000;double thick = 0.1;int count = 0; //统计折叠次数for(double i=thick; i<height; i*=2){count++;}System.out.println("折叠"+count+"次,可以折成珠穆朗玛峰的高度");}
}
实现输出如下数字三角形
//行 i j
//1 0 1
//2 1 1,2
//3 2 1,2,3
//4 3 1,2,3,4
//5 4 1,2,3,4,5
public class Homework3Test1{public static void main(String[] args){for(int i=0; i<5; i++){for(int j=1; j<=i+1; j++){System.out.print(j);}System.out.println();}}
}
//行 i j
//1 0 1
//2 1 1,2
//3 2 1,2,3
//4 3 1,2,3,4
//5 4 1,2,3,4,5
public class Homework3Test2{public static void main(String[] args){for(int i=0; i<5; i++){for(int j=1; j<=i+1; j++){System.out.print(i+1);}System.out.println();}}
}
//----1
//---222
//--33333
//-4444444
//555555555
public class Homework3Test3{public static void main(String[] args){for(int i=0; i<5; i++){//打印-//----//---//--//-////行 i j//1 0 1,2,3,4//2 1 1,2,3//3 2 1,2//4 3 1//5 4for(int j=1; j<=4-i; j++){System.out.print("-");}//打印数字//1//222//33333//4444444//555555555//行 i j//1 0 1//2 1 1,2,3//3 2 1,2,3,4,5//4 3 1,2,3,4,5,6,7//5 4 1,2,3,4,5,6,7,8,9for(int k=1; k<=2*i+1; k++){System.out.print(i+1);}System.out.println();}}
}
计算这一天是这一年的第几天
案例需求:从键盘分别输入年、月和日,判断这一天是当年的第几天。并增加输入值的合法性判断,确保输入的年份值必须大于0,月份值必须在[1,12]之间,日期值必须在[1,当月最大日期值]范围内
import java.util.Scanner;public class Homework4 {public static void main(String[] args) {Scanner sc = new Scanner(System.in);int year;while (true) {System.out.println("请输入年:");year = sc.nextInt();if (year > 0) {break;} else {System.out.println("年输入有误");}}int month;while (true) {System.out.println("请输入月:");month = sc.nextInt();if (month >= 1 && month <= 12) {break;} else {System.out.println("月输入有误");}}int days;if (month == 2) {if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {days = 29;} else {days = 28;}} else if (month == 4 || month == 6 || month == 9 || month == 11) {days = 30;} else {days = 31;}int day;while (true) {System.out.println("请输入日:");day = sc.nextInt();if (day > 0 && day <= days) {break;} else {System.out.println("日输入有误");}}int totalDays = day;for (int i = 0; i < month; i++) {if (i == 2) {if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {totalDays += 29;} else {totalDays += 28;}} else if (i == 4 || i == 6 || i == 9 || i == 11) {totalDays += 30;} else {totalDays += 31;}}System.out.println(totalDays);}
}
计算这一天是在打鱼还是晒网
案例需求:假设从2000年1月1日开始三天打鱼,两天晒网,从键盘输入今天的日期年、月和日,增加输入值的合法性判断,确保输入的年份值必须大于0,月份值必须在[1,12]之间,日期值必须在[1,当月最大日期值]范围内,显示今天是打鱼还是晒网
import java.util.Scanner;public class HomeworkTest2 {public static void main(String[] args) {Scanner sc = new Scanner(System.in);int year;while (true) {System.out.println("请输入年:");year = sc.nextInt();if (year >= 2000) {break;} else {System.out.println("年份不合法!");}}int month;while (true) {System.out.println("请输入月:");month = sc.nextInt();if (month >= 1 && month <= 12) {break;} else {System.out.println("月份不合法!");}}int days;if (month == 2) {if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {days = 29;} else {days = 28;}} else if (month == 4 || month == 6 || month == 9 || month == 11) {days = 30;} else {days = 31;}int day;while (true) {System.out.println("请输入日:");day = sc.nextInt();if (day >= 1 && day <= days) {break;} else {System.out.println("日期不合法!");}}int totalDays = day;for (int i = 2000; i < year; i++) {if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {totalDays += 366;} else {totalDays += 365;}}for (int i = 0; i < month; i++) {if (i == 2) {if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {totalDays += 29;} else {totalDays += 28;}} else if (i == 4 || i == 6 || i == 9 || i == 11) {totalDays += 30;} else {totalDays += 31;}}if (totalDays % 5 == 1 || totalDays % 5 == 2 || totalDays % 5 == 3) {System.out.println("今天是打鱼");} else {System.out.println("今天是晒网");}}
}
打印x对称图形
开发提示:
平面图形涉及到有行有列,考虑嵌套 for 循环
一个外循环控制行,一个内循环控制输出内容
在内循环中,根据变量的变化规律,判断输出O还是*
//7*7//行 i O
//1 0 1,7
//2 1 2,6
//3 2 3,5
//4 3 4
//5 4 5,3
//6 5 6,2
//7 6 7,1public class HomeworkTest3{public static void main(String[] args){for(int i=0; i<7; i++){for(int j=1; j<=7; j++){if(j==i+1 || j==7-i){System.out.print("O");}else{System.out.print("*");}}System.out.println();}}
}
打印空心菱形
开发提示:
平面图形涉及到有行有列,考虑嵌套 for 循环
一个外循环控制行,两个内循环控制输出内容
一个内循环负责输出-,另一个内循环输出*或-
//9*9//----*----
//---*-*---
//--*---*--
//-*-----*-
//*-------*
//-*-----*-
//--*---*--
//---*-*---
//----*----
public class HomeworkTest4{public static void main(String[] args){//上半部分//----*---- //---*-*--- //--*---*--//-*-----*-//*-------*//行 i * //1 0 5//2 1 4,6//3 2 3,7//4 3 2,8for(int i=0; i<4; i++){for(int j=1; j<=9; j++){if(j==i+5 || j==5-i){System.out.print("*");}else{System.out.print(" ");}}System.out.println();}//下半部分//-*-----*-//--*---*--//---*-*---//----*----//行 i * //1 0 9,1//2 1 8,2//3 2 7,3//4 3 6,4//5 4 5for(int i=0; i<5; i++){for(int j=1; j<=9; j++){if(j==i+1 || j==9-i){System.out.print("*");}else{System.out.print(" ");}}System.out.println();}}
}
day05
月份
用一个数组,存储1~12月的英文,从键盘输入1~12,显示对应的单词
import java.util.Scanner;public class Homework1 {public static void main(String[] args) {String[] arr = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};Scanner sc = new Scanner(System.in);System.out.println("请输入数字(1~12):");int num = sc.nextInt();if (num >= 1 && num <= 12){System.out.println(num + "月份的英文为" + arr[num - 1]);} else {System.out.println("数字输入有误!");}}
}
打印扑克牌
遍历输出一副扑克牌
String[] hua = {"黑桃", "红桃", "梅花", "方片"};
String[] dian = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"};
public class Homework2 {public static void main(String[] args) {String[] hua = {"黑桃", "红桃", "梅花", "方片"};String[] dian = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"};String[] pu = new String[hua.length * dian.length + 2];//i控制花色,j控制点数,k控制牌数for (int i = 0, k = 0; i < hua.length; i++) {for (int j = 0; j < dian.length; j++, k++) {pu[k] = hua[i] + dian[j];}}pu[pu.length - 2] = "大王";pu[pu.length - 1] = "小王";for (int i = 0; i < pu.length; i++) {if(i % 13 == 0 && i != 0){System.out.println();}System.out.print(pu[i] + " ");}}
}
正序和逆序输出26个英文字母
要求使用 int 类型的数组存储26个英文字母,并分别用正序和逆序方式显示输出,要求10个为一行
public class Homework3 {public static void main(String[] args) {char[] arr = new char[26];for (int i = 0; i < arr.length; i++) { arr[i] = (char)('a' + i);}//正序System.out.println("小写字母正序排序:");int count = 0;for (int i = 0; i < arr.length; i++) {count++;if(count == 10 || i == arr.length - 1){System.out.println(arr[i]);count = 0;}else if(count < 10){System.out.print(arr[i] + ",");}}//逆序System.out.println("小写字母逆序排序:");count = 0;for (int i = arr.length - 1; i >= 0; i--) {count++;if(count == 10 || i == 0){System.out.println(arr[i]);count = 0;}else if(count < 10){System.out.print(arr[i] + ",");}}}
}
随机生成一组验证码
随机生成一组验证码,验证码由大小写字母和10个阿拉伯数字字符中的任意6位组成
开发提示:
声明一个 char[] 数组,并存储26个大小写字母和10个阿拉伯数字字符
随机生成6位下标,取出里面的字符组成验证码
public class Homework4 {public static void main(String[] args) {char[] arr = new char[26 * 2 + 10];for (int i = 0; i < 26; i++) { //[0, 25] 存储小写字母arr[i] = (char)('a' + i);}for (int i = 0; i < 26; i++) { //[26, 51] 存储大写字母arr[26 + i] = (char)('A' + i);}for (int i = 0; i < 10; i++) { //[52, 61] 存储大写字母arr[52 + i] = (char)('0' + i);}String code = "";int index;for (int i = 0; i < 6; i++) { index =(int)(Math.random() * arr.length);code += arr[index];}System.out.println("随机验证码:" + code);}
}
判断数组中的元素值是否对称
判断某个数组是否是对称数组,即数组正序遍历和倒序遍历的结果是一样的
开发提示:数组中元素首尾比较
public class Homework5 {public static void main(String[] args) {int[] arr = {1, 2, 3, 4, 3, 2, 1};boolean flag = true;for (int left = 0, right = arr.length - 1; left < right; left++, right--) {if(arr[left] != arr[right]){flag = false;break;}}System.out.println("是否对称:" + flag);}
}
打鱼还是晒网
假设张三从1990年1月1日开始执行三天打鱼两天晒网,5天一个周期,风雨无阻,那么李四想要找张三玩,需要从键盘输入年、月和日后,判断这一天张三是在打鱼还是晒网
开发提示:使用一个数组存储平年的总天数和12个月的总天数
import java.util.Scanner;public class Test1 {public static void main(String[] args) {Scanner sc = new Scanner(System.in);System.out.println("请输入年份:");int year = sc.nextInt();System.out.println("请输入月份:");int month = sc.nextInt();System.out.println("请输入日期:");int day = sc.nextInt();int[] arr = {365, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};int days = day;for (int i = 1990; i < year; i++) {days += arr[0];if(i % 4 == 0 && i % 100 != 0 || i % 400 == 0){days ++;}}if(year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {arr[2] = 29;}for (int i = 1; i < month; i++) {days += arr[i];}if(day % 5 == 1 || day % 5 == 2 || day % 5 == 3){System.out.println("打鱼");}System.out.println("晒网");}
}
模拟大乐透
大乐透(前区“35选5”+后区“12选2”),即前区在1~35之间的号码中随机选取5个,后区在1~12之间的号码中随机选取2个,组成一期的中奖号码,请用程序模拟产生一组大乐透中奖号码
开发提示:
声明一个 int 类型的数组 front,长度为35,默认值都是0
声明一个 int 类型的数组 after,长度为12,默认值都是0
随机产生[0, 35)之间的整数:如果随机产生的是0,那么就把 front[0] 修改为1,如果随机产生的是5,那么就把 front[5] 修改为1,如果随机产生的是10,就把 front[10] 修改为1,但是如果本次随机产生的是5,而 front[5] 已经是1,那么需要重新随机产生一个整数,用这种方式把 front 数组的5个元素修改为1
随机产生[0,12)之间的整数,使用同样的方式,把 after 数组的2个元素修改为1
遍历 front 和 after 数组,输出大乐透中奖号码,判断 front 和 after 数组元素是否为1,如果为1,就显示它的下标+1
public class Test2 {public static void main(String[] args) {int[] front = new int[35];for (int i = 0; i < 5; i++) {int index;do {index = (int) (Math.random() * front.length);} while (front[index] == 1);front[index] = 1;}int[] after = new int[12];for (int i = 0; i < 2; i++) {int index;do {index = (int) (Math.random() * after.length);} while (after[index] == 1);after[index] = 1;}System.out.println("本期大乐透中奖号码:");System.out.print("前区:");for (int i = 0; i < front.length; i++) {if(front[i] == 1){System.out.print((i + 1) + " ");}}System.out.println();System.out.print("后区:");for (int i = 0; i < after.length; i++) {if(after[i] == 1){System.out.print((i + 1) + " ");}}}
}
统计字符出现次数
英语中最长的单词是 pneumonoultramicroscopicsilicovolcanoconiosis,意思是肺尘病、矽肺病,一共有45个英文字母,现在要求统计这个单词中出现了哪些字母,以及它们出现的次数,并且找出出现次数最多的字母
开发提示
使用 String 类型的变量 word 存储英语单词 pneumonoultramicroscopicsilicovolcanoconiosis
通过 word.toCharArray() 可以根据字符串 word 得到一个 char[] 类型的数组,其中 toCharArray() 是 String 类型提供的系统函数,就像 Math.random() 等函数一样,它的作用就是创建一个 char[] 数组,并把字符串中的每一个字符依次存储到这个 char[] 数组中
声明一个 int 类型的数组 counts,长度为26,分别用来记录26个字母出现的次数,counts[0]记录的是 a 字母的次数,counts[1] 记录的是 b 字母的次数,依次类推
public class Test3 {public static void main(String[] args) {String word = "pneumonoultramicroscopicsilicovolcanoconiosis";char[] arr = word.toCharArray();int[] count = new int[26];for (int i = 0; i < arr.length; i++) {count[arr[i] - 97]++;}//单词中出现了如下字母System.out.println("单词中出现了如下字母:");for (int i = 0; i < count.length; i++) {if (count[i] != 0){System.out.println(((char) (i + 97)) + ":" + count[i]);}}//出现次数最多的字母是:System.out.println("出现次数最多的字母是:");int max = count[0];for (int i = 0; i < count.length; i++) {if(max < count[i]){max = count[i];}}for (int i = 0; i < count.length; i++) {if(count[i] == max){System.out.println((char)(i + 97));}}}
}
统计低于平均分的学生人数
先从键盘输入本组学员的人数,再从键盘输入本组学员的姓名和成绩,最后统计
本组学员的平均分
低于平均分的学员人数
哪些学员低于平均分
最高分和最低分分别是谁
import java.util.Scanner;public class Test4 {public static void main(String[] args) {Scanner sc = new Scanner(System.in);System.out.println("请输入本组学员的人数:");int num = sc.nextInt();String[] name = new String[num];double[] score = new double[num];for (int i = 0; i < num; i++) {System.out.println("请输入第" + (i+1) + "个学员的姓名:");name[i] = sc.next();System.out.println("请输入第" + (i+1) + "个学员的成绩:");score[i] = sc.nextDouble();}//本组学员的平均分double scores = 0.0;for (int i = 0; i < num; i++) {scores += score[i];}double aveSco = scores / num;System.out.println("本组学员的平均分:" + aveSco);//低于平均分的学员人数int lowAveScoNum = 0;for (int i = 0; i < num; i++) {if(score[i] < aveSco){lowAveScoNum++;}}System.out.println("低于平均分的学员人数:" + lowAveScoNum);//哪些学员低于平均分System.out.print("哪些学员低于平均分:");for (int i = 0; i < num; i++) {if(score[i] < aveSco){System.out.print(name[i] + " ");}}System.out.println();//最高分是谁double max = score[0];int maxIndex = 0;for (int i = 1; i < num; i++) {if(max < score[i]){max = score[i];maxIndex = i;}}System.out.println("最高分是谁:" + name[maxIndex]);//最低分是谁double min = score[0];int minIndex = 0;for (int i = 1; i < num; i++) {if(min > score[i]){min = score[i];minIndex = i;}}System.out.println("最低分是谁:" + name[minIndex]);}
}
day06
随机产生偶数并排序
随机产生10个[1, 100]之间的偶数存储到数组中,并按照从小到大排序输出
import java.util.Arrays;public class Homework1 {public static void main(String[] args) {int[] arr = new int[10];for (int i = 0; i < arr.length; i++) {arr[i] = (int)(Math.random() * 50 + 1) * 2; //随机产生10个[1, 100]的偶数}System.out.print("排序前:");for (int i = 0; i < arr.length; i++) {System.out.print(arr[i] + " ");}System.out.println();//i=1 0-1 1-2 ... 8-9//i=2 0-1 1-2 ... 7-8//...//i=9 0-1for (int i = 1; i < arr.length; i++) {for (int j = 0; j < arr.length - i; j++) {if(arr[j] > arr[j + 1]){int temp = arr[j + 1];arr[j + 1] = arr[j];arr[j] = temp;}}}System.out.print("排序后:");for (int i = 0; i < arr.length; i++) {System.out.print(arr[i] + " ");}System.out.println();}
}
判断单词是否是回文单词
从键盘输入一个单词,判断它是否是回文单词
开发提示:
从键盘输入一个单词,存放到一个 String 类型的变量 word 中
通过 word.toCharArray() 可以根据字符串 word 得到一个 char[] 类型的数组
其中 toCharArray() 是 String 类型提供的系统函数,就像 Math.random() 等函数一样,它的作用就是创建一个 char[] 数组,并把字符串中的每一个字符依次存储到这个 char[] 数组中
判断数组元素是否首尾对应相等,如果是,那么你输入的单词就是回文单词,否则就不是
import java.util.Scanner;
public class Homework2 {public static void main(String[] args) {Scanner sc = new Scanner(System.in);System.out.print("请输入一个单词:");String word = sc.next();char[] arr = word.toCharArray();boolean flag = true;for (int left = 0, right = arr.length - 1; left < right; left++, right--) {if(arr[left] != arr[right]){flag = false;break;}}if(flag){System.out.println(word + "是回文单词");}else{System.out.println(word + "不是回文单词");}}
}
查找满分学员
先从键盘输入本组学员的人数,再从键盘输入本组学员的姓名和成绩,显示学员姓名和成绩,最后查找是否有满分(100)学员,如果有,显示姓名,如果没有,则显示没有满分学员
import java.util.Scanner;
public class Homework3 {public static void main(String[] args) {Scanner sc = new Scanner(System.in);System.out.println("请输入本组学员的人数:");int num = sc.nextInt();String[] names = new String[num];Double[] scores = new Double[num];for (int i = 0; i < num; i++) {System.out.println("请输入第" + (i+1) + "个学员的姓名:");names[i] = sc.next();System.out.println("请输入第" + (i+1) + "个学员的成绩:");scores[i] = sc.nextDouble();}System.out.println("所有学员的成绩:");for (int i = 0; i < num; i++) {System.out.println(names[i] + ":" + scores[i]);}System.out.println("本班满分学员:");boolean flag = false;for (int i = 0; i < num; i++) {if(scores[i] == 100){flag = true;System.out.println(names[i]);}}if(!flag){System.out.println("没有");}}
}
查字
公司年会有一个寻找锦鲤的游戏,每一个员工随意写一个字,如果在“锦鲤”词库中有这个字,那么就奖励500元锦鲤红包,否则就没有,每人只能玩一次
现有锦鲤字库如下,它们按照 Unicode 编码值从小到大排序
char[] koiFishWords = {'一', '今', '地', '定', '尚', '年', '开', '我', '果', '火', '爱', '硅', '结', '花', '谷', '遍'};
import java.util.Scanner;
public class Homework4 {public static void main(String[] args) {char[] koiFishWords = {'一', '今', '地', '定', '尚', '年', '开', '我', '果', '火', '爱', '硅', '结', '花', '谷', '遍'};Scanner sc = new Scanner(System.in);System.out.println("请输入一个字:");char word = sc.next().charAt(0);boolean flag = false;for (int i = 0; i < koiFishWords.length; i++) {if(word == koiFishWords[i]){flag = true;break;}}if(flag){System.out.println("中奖了!奖励500元锦鲤红包!");}else{System.out.println("没中奖!");}}
}
找出出现奇数次的数
已知某个数组中只有1个数字的次数出现奇数次,请找出这个数字
开发提示:
因为对于任意一个数 k,有 k ^ k=0,k ^ 0=k,所以将 arr 中所有元素进行异或,那么个数为偶数的元素异或后都变成了0,只留下了个数为奇数的那个元素
public class Homework5 {public static void main(String[] args) {int[] arr = {2, 8, 1, 1, 6, 5, 6, 2, 6, 8, 6, 1, 2, 1, 5};int num = arr[0];for (int i = 1; i < arr.length; i++) {num ^= arr[i];}System.out.println("出现奇数次的是:" + num);}
}
找数组平衡树
判断数组中是否存在一个值,其左侧的值累加等于其右侧的值累加,如果存在,找出这个值,如果不存在,则显示不存在,比如:
[1, 2, 5, 3, 2, 4, 2],结果为:第4个值3
[9, 6, 8, 8, 7, 6, 9, 5, 2, 5],结果为:不存在
public class Test1 {public static void main(String[] args) {int[] arr = {9, 6, 8, 8, 7, 6, 9, 5, 2, 5};boolean flag = false;for (int mid = 0; mid < arr.length; mid++) {int leftSum = 0;int rightSum = 0;for (int i = 0; i < mid; i++) {leftSum += arr[i];}for (int i = mid + 1; i < arr.length; i++) {rightSum += arr[i];}if(leftSum == rightSum){flag = true;System.out.println("平衡数是第" + (mid + 1) + "个值" + arr[mid]);}}if(!flag) {System.out.println("不存在平衡数");}}
}
左奇右偶
现有一个长度为10的整数数组{26, 67, 49, 38, 52, 66, 7, 71, 56, 87},现在需要对元素重新排序,使得所有的奇数保存到数组左边,所有的偶数保存到数组右边
开发提示:
左边的偶数与右边的奇数换位置
定义两个变量 left 和 right,从左边开始查找偶数的位置,找到后用 left 记录,从右边开始找奇数的位置,找到后用 right 记录,如果 left<right,那么就交换,然后在上一次的基础上继续查找,直到 left 与 right 擦肩
public class Test2 {public static void main(String[] args) {int[] arr = {26, 67, 49, 38, 52, 66, 7, 71, 56, 87};System.out.println("原数组:");for (int i = 0; i < arr.length; i++) {System.out.print(arr[i] + " ");}System.out.println();for (int left = 0, right = arr.length - 1; left < right; ) {while (arr[left] % 2 != 0){left++;}while (arr[right] % 2 == 0){right--;}if(left < right){int temp = arr[right];arr[right] = arr[left];arr[left] = temp;}}System.out.println("排序后:");for (int i = 0; i < arr.length; i++) {System.out.print(arr[i] + " ");}System.out.println();}
}
查找数组中个数过半的数字
有一个长度为10的整型元素的数组 arr,其中有一个元素出现次数超过 n/2,求这个元素
开发提示:
对数组进行排序
取占据数组中间位置的元素,如果某个数字出现的次数过半,那么给数组排序后,这个数字一定会占据数组中间的位置
统计占据数组中间位置的元素实际出现的次数,这样就不用统计每一个数字出现的次数了
import java.util.Arrays;public class Test3 {public static void main(String[] args) {int[] arr = {1, 2, 3, 2, 2, 2, 5, 4, 2};//i=1 0-1 1-2 ... 8-9//i=2 0-1 1-2 ... 7-8//...//i=9 0-1 System.out.println("从小到大排序:");for (int i = 1; i < arr.length; i++) {for (int j = 0; j < arr.length - i; j++) {if(arr[j] > arr[j + 1]){int temp = arr[j + 1];arr[j + 1] = arr[j];arr[j] = temp;}}}for (int i = 0; i < arr.length; i++) {System.out.print(arr[i] + " ");}System.out.println();int mid = arr[arr.length / 2];int count = 0;for (int i = 0; i < arr.length; i++) {if(arr[i] == mid){count++;}}if(count >= arr.length / 2){System.out.println("数组中个数过半的是" + mid + ",共出现了" + count + "次");}else{System.out.println("数组中不存在个数过半的数字");}}
}
求数组中元素的最短距离
随机产生10个[0, 100)之间整数存储到数组中,找到数组中的两个元素 x 和 y,使得 (x-y) 绝对值最小
开发提示:
将数组进行排序
求相邻元素差,差值最小值就是最短距离
import java.util.Arrays;public class Test {public static void main(String[] args) {int[] arr = new int[10];for (int i = 0; i < arr.length; i++) {arr[i] = (int) (Math.random() * 100);}System.out.println("排序前:" + Arrays.toString(arr));for (int i = 0; i < arr.length - 1; i++) {for (int j = 0; j < arr.length - 1 - i; j++) {if(arr[j] > arr[j + 1]) {int temp = arr[j + 1];arr[j + 1] = arr[j];arr[j] = temp;}}}System.out.println("排序后:" + Arrays.toString(arr));int min = arr[1] - arr[0];for (int i = 1; i < arr.length - 1; i++) {if((arr[i + 1] - arr[i]) < min) {min = (arr[i + 1] - arr[i]);}}System.out.println("最短距离:" + min);}
}
day07
员工
声明员工类 Employee,包含属性:编号、姓名、年龄和薪资,在测试类的 main 方法中,创建2个员工对象,为属性赋值,打印两个员工的信息
package Homework1;public class Test1 {public static void main(String[] args) {Employee e1 = new Employee();e1.id = 1;e1.name = "张三";e1.age = 23;e1.salary = 10000.0;System.out.println("第1个员工的编号:" + e1.id + ",姓名:" + e1.name + ",年龄:" + e1.age + ",薪资:" + e1.salary);Employee e2 = new Employee();e2.id = 2;e2.name = "李四";e2.age = 22;e2.salary = 11000.0;System.out.println("第2个员工的编号:" + e2.id + ",姓名:" + e2.name + ",年龄:" + e2.age + ",薪资:" + e2.salary);}
}class Employee {int id;String name;int age;double salary;
}
日期类
声明一个日期类 MyDate,包含属性:年、月和日,在测试类的 main 方法中,创建3个日期对象,一个是出生日期,一个是入学日期,一个是毕业日期,打印显示
package Homework2;public class Test2 {public static void main(String[] args) {MyDate m1 = new MyDate();m1.year = 1997;m1.month = 9;m1.day = 25;System.out.println("出生日期:" + m1.year + "年" + m1.month + "月" + m1.day + "日");MyDate m2 = new MyDate();m2.year = 2021;m2.month = 3;m2.day = 14;System.out.println("入学日期:" + m2.year + "年" + m2.month + "月" + m2.day + "日");MyDate m3 = new MyDate();m3.year = 2019;m3.month = 7;m3.day = 1;System.out.println("毕业日期:" + m3.year + "年" + m3.month + "月" + m3.day + "日");}
}class MyDate {int year;int month;int day;
}
三角形
声明一个三角形类 Triangle,包含属性:a、b和c,都是 double 类型,表示三条边,包含几个方法:
1.boolean isTriangle():判断是否是一个三角形
2.boolean isRightTriangle():判断是否是一个直角三角形
3.boolean isIsoscelesTriangle():判断是否是一个等腰三角形
4.boolean isEquilateralTriangle():判断是否是一个等边三角形
5.double area():根据三条边,用海伦公式求面积
6.double perimeter():求周长
在测试类的 main 方法中创建三角形对象,将三角形的三条边设置为3、4和5,调用方法测试
public class Test {public static void main(String[] args) {Triangle t = new Triangle();t.a = 3;t.b = 4;t.c = 5;System.out.println("是三角形吗?" + t.isTriangle()); //trueSystem.out.println("是直角三角形吗?" + t.isRightTriangle()); //trueSystem.out.println("是等腰三角形吗?" + t.isIsoscelesTriangle()); //falseSystem.out.println("是等边三角形吗?" + t.isEquilateralTriangle()); //falseSystem.out.println("面积:" + t.area()); //6.0System.out.println("周长:" + t.perimeter()); //12.0}
}class Triangle {double a;double b;double c;boolean isTriangle() {return (a>0 && b>0 && c>0) && (a+b>c && b+c>a && c+a>b);}boolean isRightTriangle() {return isTriangle() && (a*a+b*b==c*c || b*b+c*c==a*a || c*c+a*a==b*b);}boolean isIsoscelesTriangle() {return isTriangle() && (a==b || b==c || c==a);}boolean isEquilateralTriangle() {return isTriangle() && (a==b && b==c);}double area() {if (isTriangle()) {double p = (a+b+c) / 2;return Math.sqrt(p * (p-a) * (p-b) * (p-c));}else {return 0.0;}}double perimeter() {if (isTriangle()) {return (a + b + c);}else {return 0.0;}}
}
日期类
声明一个日期类 MyDate:
1.包含属性:年、月和日
2.boolean isLeapYear():判断是否是闰年
3.String monthName():根据月份值,返回对应的英语单词
4.int totalDaysOfMonth():返回这个月的总天数
5.int totalDaysOfYear():返回这一年的总天数
6.int daysOfTheYear():返回这一天是当年的第几天
在测试类的 main 方法中,创建 MyDate 对象,赋值为当天日期值,调用方法测试
public class Test {public static void main(String[] args) {MyDate date = new MyDate();date.year = 2023;date.month = 6;date.day = 30;System.out.println("这年是闰年吗:" +date.isLeapYear()); //falseSystem.out.println("这月对应的英文单词:" +date.monthName()); //JuneSystem.out.println("这月的总天数:" + date.totalDaysOfMonth()); //30System.out.println("这年的总天数:" + date.totalDaysOfYear()); //365System.out.println("这天是这年的第几天:" +date.daysOfTheYear()); //212}
}class MyDate {int year;int month;int day;boolean isLeapYear() {return (year%4==0 && year%100!=0 || year%400==0);}String monthName() {String[] monthNames = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};return monthNames[month - 1];}int totalDaysOfMonth() {if(month == 2) {if(isLeapYear()) {return 29;}else {return 28;}}else if(month==4 || month==6 || month==9 || month==11) {return 30;}else {return 31;}}int totalDaysOfYear() {return isLeapYear() ? 366:365;}int daysOfTheYear() {int daysOfTheYear = day;for (int i = 0; i < month; i++) {if(i == 2) {if(isLeapYear()) {daysOfTheYear += 29;}else {daysOfTheYear += 28;}}else if(i==4 || i==6 || i==9 || i==11) {daysOfTheYear += 30;}else {daysOfTheYear += 31;}}return daysOfTheYear;}
}
数组工具类
声明一个数组工具类 ArrayTools,包含如下方法:
1.int sum(int[] arr):求所有元素的总和
2.int max(int[] arr):求所有元素的最大值
3.int indexOf(int[] arr, int value):查找 value 在 arr 数组中第一次出现的下标,如果不存在返回-1
4.int lastIndexOf(int[] arr, int value):查找 value 在 arr 数组中最后一次出现的下标,如果不存在返回-1
在测试类的 main 方法中,调用方法测试
package Homework5;public class Test5 {public static void main(String[] args) {ArrayTools a = new ArrayTools();int[] arr = {1, 2, 10, 4, 5, 10, 7, 8, 9, 10};System.out.println("所有元素的总和:" + a.sum(arr));System.out.println("所有元素的最大值:" + a.max(arr));System.out.println("10在数组中第一次出现的下标:" + a.indexOf(arr, 10));System.out.println("10在数组中最后一次出现的下标:" + a.lastIndexOf(arr, 10));}
}class ArrayTools {int sum(int arr[]){int sum = 0;for (int i = 0; i < arr.length; i++) {sum += arr[i];}return sum;}int max(int[] arr){int max = arr[0];for (int i = 1; i < arr.length; i++) {if(max < arr[i]){max = arr[i];}}return max;}int indexOf(int[] arr, int value){for (int i = 0; i < arr.length; i++) {if (arr[i] == value) {return i;}}return -1;}int lastIndexOf(int[] arr, int value){for (int i = arr.length - 1; i >= 0; i--) {if(arr[i] == value){return i;}}return -1;}
}
公民类
声明一个日期类 MyDate:
1.包含属性:年、月和日
2.包含 String dateToString() 方法,返回“ xxx 年 xxx 月 xxx 日”
声明公民类 Citizen:
1.包含属性:String 类型的姓名、MyDate 类型的生日和 String 类型的身份证号
2.包含 String.getInfo()方法,返回“姓名:xx,生日:xx 年 xx 月 xx 日,身份证号:xx”
3.包含 void setBirthday(int year, int month, int day):设置生日
在测试类的main方法中,创建对象并打印信息
public class Test {public static void main(String[] args) {Citizen c = new Citizen();c.name = "张三";c.setBirthday(1997, 5, 17);c.id = "123456789";System.out.println(c.getInfo()); //姓名:张三, 生日:1997年5月17日, 身份证号:123456789}
}class MyDate {int year;int month;int day;String dataToString() {return year + "年" + month + "月" + day + "日";}
}class Citizen {String name;MyDate birthday;String id;String getInfo() {return "姓名:" + name + ", 生日:" + birthday.dataToString() + ", 身份证号:" + id;}void setBirthday(int year, int month, int day) {birthday = new MyDate();birthday.year = year;birthday.month = month;birthday.day = day;}
}
数组工具类
声明一个数组工具类 ArrayTools,包含如下方法:
1.int max(int[] arr):找出所有元素的最大值
2.int valueCount(int[] arr, int value):查找 value 在 arr 数组中出现的次数,如果不存在返回0
3.int[] maxIndex(int[] arr):找出所有最大值
4.void sort(int[] arr):实现元素从小到大排序
5.void reverse(int[] arr, int start, int end):反转 [start, end] 范围内的元素
6.int[] copyOf(int[] arr, int newLength):复制 arr 数组,新数组的长度 newLength,如果 newLength <= arr.length,则复制 arr 数据的 [0, newLength-1] 范围的元素,如果 newLength > arr.length,则复制 arr 数组的所有元素到新数组,剩下的元素默认即可
7.boolean equals(int[] arr1, int[] arr2):判断两个数组的长度和元素是否都相等,如果两个数组以相同顺序包含相同元素,则两个数组是相等的
8.void fill(int[] arr, int start, int end, int value):将 arr 数组 [start, end] 范围的元素赋值为 value
9.String toString(int[] arr):将元素拼接为“{元素1, 元素2, ...}”的字符串返回
在测试类的 main 方法中,调用方法测试
public class Test {public static void main(String[] args) {int[] arr = {1, 2, 10, 4, 5, 10, 7, 8, 9, 10};ArrayTools tools = new ArrayTools();System.out.println(tools.toString(arr)); //{1, 2, 10, 4, 5, 10, 7, 8, 9, 10}int max = tools.max(arr);System.out.println("所有元素的最大值:" + max); //10System.out.println("最大值在数组中出现的次数:" + tools.valueCount(arr, max)); //3int[] maxIndex = tools.maxIndex(arr);System.out.println("最大值在数组中出现的位置:" + tools.toString(maxIndex)); //{2, 5, 9}//1, 2, 10, 4, 5, 10, 7, 8, 9, 10//0, 1, 2, 3, 4, 5, 6, 7, 8, 9tools.sort(arr);System.out.println("元素从小到大排序:" + tools.toString(arr)); //{1, 2, 4, 5, 7, 8, 9, 10, 10, 10}tools.reverse(arr, 3, 7);System.out.println("反转[3, 7]范围内的元素:" + tools.toString(arr)); //{1, 2, 4, 10, 9, 8, 7, 5, 10, 10}//1, 2, 4, 5, 7, 8, 9, 10, 10, 10//0, 1, 2, 3, 4, 5, 6, 7, 8, 9int[] newArr = tools.copyOf(arr, 5);System.out.println("复制数组的前5个元素:" + tools.toString(newArr)); //{1, 2, 4, 10, 9}System.out.println("两个数组的长度和元素是否都相等:" + tools.equals(arr, newArr)); //falsetools.fill(arr, 3, 7, 10);System.out.println("将[3, 7]范围的元素赋值为10:" + tools.toString(arr)); //{1, 2, 4, 10, 10, 10, 10, 10, 10, 10}//1, 2, 4, 10, 9, 8, 7, 5, 10, 10//0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
}class ArrayTools {int max(int[] arr) {int max = arr[0];for (int i = 1; i < arr.length; i++) {if(max < arr[i]) {max = arr[i];}}return max;}int valueCount(int[] arr, int value) {int count = 0;for (int i = 0; i < arr.length; i++) {if(arr[i] == value) {count++;}}return count;}int[] maxIndex(int[] arr) {int[] maxIndex = new int[valueCount(arr, max(arr))];for (int i = 0, j = 0; i < arr.length; i++) {if(arr[i] == max(arr)) {maxIndex[j] = i;j++;}}return maxIndex;}void sort(int[] arr) {for (int i = 0; i < arr.length-1; i++) {for (int j = 0; j < arr.length-1-i; j++) {if(arr[j] > arr[j+1]) {int temp = arr[j+1];arr[j+1] = arr[j];arr[j] = temp;}}}}void reverse(int[] arr, int start, int end) {for (int i = 0; i < (end - start) / 2 ; i++) {int temp = arr[start + i];arr[start + i] = arr[end - i];arr[end - i] = temp;}}int[] copyOf(int[] arr, int newLength) {int[] newArr = new int[newLength];for (int i = 0; i < newArr.length && i < arr.length; i++) {newArr[i] = arr[i];}return newArr;}boolean equals(int[] arr1, int[] arr2) {if(arr1.length == arr2.length) {for (int i = 0; i < arr1.length; i++) {if(arr1[i] != arr2[2]){return false;}}return true;}else {return false;}}void fill(int[] arr, int start, int end, int value) {for (int i = start; i <= end ; i++) {arr[i] = value;}}String toString(int[] arr) {String s = "{";for (int i = 0; i < arr.length; i++) {if(i != arr.length-1) {s += arr[i] + ", ";}else {s += arr[i];}}s += "}";return s;}
}
day08
可变参数
声明数学工具类 MathTools,包含如下方法:
1.boolean isEven(int... nums):判断 0~n 个整数是否都是偶数,如果都是偶数,返回 true,否则返回 false
2.boolean isPositive(int... nums):判断 0~n 个整数是否都是正数,如果都是正数,返回 true,否则返回 false
3.int[] toArray(int... nums):将 0~n 个整数放到一个 int[] 数组中,并返回数组
在测试类的 main 方法中测试
package Homework1;import java.util.Arrays;public class Test1 {public static void main(String[] args) {MathTools tools = new MathTools();int[] i1 = {1, 2, 3, 4};int[] i2 = {2, 4, 6, 8};System.out.println("是否都是偶数:" + tools.isEven(i1)); //falseSystem.out.println("是否都是偶数:" + tools.isEven(i2)); //trueint[] i3 = {-1, 2, -3, 4};int[] i4 = {1, 2, 3, 4};System.out.println("是否都是正数:" + tools.isPositive(i3)); //falseSystem.out.println("是否都是正数:" + tools.isPositive(i4)); //trueint[] i5 = {1, 2, 3, 4, 5};int[] arr = tools.toArray(i5);System.out.println("数组:" + Arrays.toString(arr)); //[1, 2, 3, 4, 5]}
}class MathTools {boolean isEven(int... nums){for (int i = 0; i < nums.length; i++) {if(nums[i]%2 !=0){return false;}}return true;}boolean isPositive(int... nums){for (int i = 0; i < nums.length; i++) {if(nums[i] <= 0){return false;}}return true;}int[] toArray(int... nums){int[] arr = new int[nums.length];for (int i = 0; i < arr.length; i++) {arr[i] = nums[i];}return arr;}
}
重载方法
声明一个数组工具类 ArrayTools,包含如下方法:
1.int binarySearch(int[] arr, int value):使用二分查找法在 arr 数组中查找 value 的下标,如果 value 不存在,就返回-1,如果数组 arr 不是有序的,结果将不一定正确
2.int binarySearch(char[] arr, char value):使用二分查找法在 arr 数组中查找 value 的下标,如果 value 不存在,就返回-1,如果数组 arr 不是有序的,结果将不一定正确
3.int binarySearch(double[] arr, double value):使用二分查找法在 arr 数组中查找 value 的下标,如果 value 不存在,就返回-1,如果数组 arr 不是有序的,结果将不一定正确
4.void sort(int[] arr):可以给 arr 数组从小到大排序,用冒泡排序实现
5.void sort(char[] arr):可以给 arr 数组从小到大排序,用冒泡排序实现
6.void sort(double[] arr):可以给 arr 数组从小到大排序,用冒泡排序实现
7.String toString(int[] arr):将元素拼接为“{元素1, 元素2, ...}”的字符串返回
8.String toString(double[] arr):将元素拼接为“{元素1, 元素2, ...}”的字符串返回
9.String toString(char[] arr):将元素拼接为“{元素1, 元素2, ...}”的字符串返回
在测试类的 main 方法中测试,例如:
int[] arr = {2, 4, 1, 3, 6}; //显示排序前后的元素,查找5
char[] letters = {'h', 'e', 'l', 'l', 'o'}; //显示排序前后的元素,查找a
double[] nums = {2.3, 1.5, 2.0, 3.5, 3.0}; //显示排序前后的元素,查找1.5
public class Test {public static void main(String[] args) {ArrayTools tools = new ArrayTools();int[] arr = {2, 4, 1, 3, 6};System.out.println("排序前:" + tools.toString(arr)); //{2, 4, 1, 3, 6}tools.sort(arr);System.out.println("排序后:" + tools.toString(arr)); //{1, 2, 3, 4, 6}System.out.println("5的位置:" + tools.binarySearch(arr, 5)); //-1char[] letters = {'h', 'e', 'l', 'l', 'o'};System.out.println("排序前:" + tools.toString(letters)); //{h, e, l, l, o}tools.sort(letters);System.out.println("排序后:" + tools.toString(letters)); //{e, h, l, l, o}System.out.println("o的位置:" + tools.binarySearch(letters, 'o')); //4double[] nums = {2.3, 1.5, 2.0, 3.5, 3.0};System.out.println("排序前:" + tools.toString(nums)); //{2.3, 1.5, 2.0, 3.5, 3.0}tools.sort(nums);System.out.println("排序后:" + tools.toString(nums)); //{1.5, 2.0, 2.3, 3.0, 3.5}System.out.println("1.5的位置:" + tools.binarySearch(nums, 1.5)); //0}
}class ArrayTools {void sort(int[] arr) {for (int i = 0; i < arr.length-1; i++) {for (int j = 0; j < arr.length-1-i; j++) {if(arr[j] > arr[j+1]) {int temp = arr[j+1];arr[j+1] = arr[j];arr[j] = temp;}}}}void sort(char[] arr) {for (int i = 0; i < arr.length-1; i++) {for (int j = 0; j < arr.length-1-i; j++) {if(arr[j] > arr[j+1]) {char temp = arr[j+1];arr[j+1] = arr[j];arr[j] = temp;}}}}void sort(double[] arr) {for (int i = 0; i < arr.length-1; i++) {for (int j = 0; j < arr.length-1-i; j++) {if(arr[j] > arr[j+1]) {double temp = arr[j+1];arr[j+1] = arr[j];arr[j] = temp;}}}}int binarySearch(int[] arr, int value) {for (int left = 0, right = arr.length - 1; left <= right; ) {int mid = left + (right - left) / 2;if(value > arr[mid]) {left = mid + 1;}else if (value < arr[mid]) {right = mid - 1;}else {return mid;}}return -1;}int binarySearch(char[] arr, char value) {for (int left = 0, right = arr.length - 1; left <= right; ) {int mid = left + (right - left) / 2;if(value > arr[mid]) {left = mid + 1;}else if (value < arr[mid]) {right = mid - 1;}else {return mid;}}return -1;}int binarySearch(double[] arr, double value) {for (int left = 0, right = arr.length - 1; left <= right; ) {int mid = left + (right - left) / 2;if(value > arr[mid]) {left = mid + 1;}else if (value < arr[mid]) {right = mid - 1;}else {return mid;}}return -1;}String toString(int[] arr) {String s = "{";for (int i = 0; i < arr.length; i++) {if(i != arr.length-1) {s += arr[i] + ", ";}else {s += arr[i];}}s += "}";return s;}String toString(char[] arr) {String s = "{";for (int i = 0; i < arr.length; i++) {if(i != arr.length-1) {s += arr[i] + ", ";}else {s += arr[i];}}s += "}";return s;}String toString(double[] arr) {String s = "{";for (int i = 0; i < arr.length; i++) {if(i != arr.length-1) {s += arr[i] + ", ";}else {s += arr[i];}}s += "}";return s;}
}
方法的参数传递机制分析
在 PassParamDemo 类中,声明如下方法,体会方法的参数传递机制
1.void doubleNumber(int num):将 num 变为原来的2倍
2.void toUpperCase(char letter):将 letter 的小写字母转为大写字母
3.void expandCircle(Circle c, double times):将 Circle 的 c 对象的半径扩大为原来的 times 倍,圆 Circle 类,包含 radius 属性
4.void doubleElement(int[] arr):将 arr 数组的元素扩大2倍
5.void grow(int[] arr):将 arr 数组的长度变为原来的2倍
package Homework3;import java.util.Arrays;public class Test3 {public static void main(String[] args) {PassParamDemo demo = new PassParamDemo();int num = 5;demo.doubleNumber(num);System.out.println(num); //5char letter = 'a';demo.toUpperCase(letter);System.out.println(letter); //aCircle c = new Circle();c.radius = 5;demo.expandCircle(c, 2);System.out.println(c.radius); //10int[] arr = {1, 2, 3};demo.doubleElement(arr);System.out.println(Arrays.toString(arr)); //[2, 4, 6]demo.grow(arr);System.out.println(Arrays.toString(arr)); //[2, 4, 6]}
}class PassParamDemo {void doubleNumber(int num){num *= 2;}void toUpperCase(char letter){letter -= 32;}void expandCircle(Circle c, double times){c.radius *= times;}void doubleElement(int[] arr){for (int i = 0; i < arr.length; i++) {arr[i] *= 2;}}void grow(int[] arr){arr = new int[arr.length * 2];}
}class Circle{int radius;
}
不死神兔
用递归实现不死神兔:故事得从西元1202年说起,话说有一位意大利青年,名叫斐波那契,在他的一部著作中提出了一个有趣的问题:假设一对刚出生的小兔一个月后就能长成大兔,再过一个月就能生下一对小兔,并且此后每个月都生一对小兔,没有发生死亡,问:现有一对刚出生的兔子2年后(24个月)会有多少对兔子?
package Homework4;public class Test4 {public static void main(String[] args) {Rabbit rabbit = new Rabbit();System.out.println(rabbit.f(24));}
}//n=1 f(1) = 1(0) = 1
//n=2 f(2) = 1(1) = 1
//n=3 f(3) = 1(2) + 1(0) = 2
//n=4 f(4) = 1(3) + 1(1) + 1(0) = 3
//n=5 f(5) = 1(4) + 1(2) + 1(1) + 1(0) + 1(0) = 5
//...
// f(n) = f(n-1) + f(n-2)
class Rabbit {long f(int n){if(n == 1 || n == 2){return 1;}else{return f(n - 1) + f (n - 2);}}
}
通项公式
通项公式如下:f(n) = n + (n-1) + (n-2) + ... + 1,其中 n 是大于等于5并且小于10000的整数,例如:f(5) = 5 + 4 + 3 + 2 + 1,请用递归的方式完成方法 long f(int n)的方法体
package Homework5;public class Test5 {public static void main(String[] args) {MyClass my = new MyClass();System.out.println(my.f(5));}
}class MyClass{long f(int n){if(n == 1){return 1;}else {return f(n-1) + n;}}}
员工对象数组
声明一个 Employee 员工类,包含属性:编号(id)、姓名(name)、薪资(salary)和年龄(age),包含如下方法:
1.String getInfo():返回员工的详细信息
2.void setInfo(int i, String n, double s, int a):可以同时给 id、name、salary和age 赋值
声明一个 EmployeeManager 员工管理类,包含:
1.Employee[] 类型的 allEmployees,长度指定为5
2.int 类型的实例变量 total,记录 allEmployees 数组实际存储的员工数量
3.boolean addEmployee(Employee emp):添加一个员工对象到 allEmployees 数组中,如果数组已满,则不添加并提示数组已满
4.Employee[] getEmployees():返回 total 个员工对象
在测试类的main中添加6个员工对象,并且遍历输出
package Homework6;public class Test6 {public static void main(String[] args) {EmployeeManager managers = new EmployeeManager();Employee e1 = new Employee();e1.setInfo(1, "张三", 10000.0, 23);System.out.println("添加e1" + (managers.addEmployee(e1) ? "成功" : "失败"));Employee e2 = new Employee();e2.setInfo(2, "李四", 12000.0, 24);System.out.println("添加e2" + (managers.addEmployee(e2) ? "成功" : "失败"));Employee e3 = new Employee();e3.setInfo(3, "王五", 15000.0, 27);System.out.println("添加e3" + (managers.addEmployee(e3) ? "成功" : "失败"));Employee e4 = new Employee();e4.setInfo(4, "赵六", 13000.0, 25);System.out.println("添加e4" + (managers.addEmployee(e4) ? "成功" : "失败"));Employee e5 = new Employee();e5.setInfo(5, "田七", 18000.0, 30);System.out.println("添加e5" + (managers.addEmployee(e5) ? "成功" : "失败"));Employee e6 = new Employee();e6.setInfo(6, "万八", 9000.0, 21);System.out.println("添加e6" + (managers.addEmployee(e6) ? "成功" : "失败"));Employee[] employees = managers.getEmployees();for (int i = 0; i < employees.length; i++) {System.out.println(employees[i].getInfo());}}
}class Employee {int id;String name;double salary;int age;String getInfo(){return "编号:" + id + ",姓名:" + name + ",薪水:" + salary + ",年龄:" + age;}void setInfo(int i, String n, double s, int a){id = i;name = n;salary = s;age = a;}
}class EmployeeManager {Employee[] allEmployees = new Employee[5];int total = 0;boolean addEmployee(Employee emp){if (total >= allEmployees.length){System.out.println("数组已满");return false;}else {allEmployees[total] = emp;total++;return true;}}Employee[] getEmployees(){Employee[] employees = new Employee[total];for (int i = 0; i < employees.length; i++) {employees[i] = allEmployees[i];}return employees;}
}
day09
普通员工类
普通员工类 Employee:
1.提供私有属性:姓名,性别,年龄,工资,电话,邮箱
2.提供 get/set 方法
3.提供 String getInfo() 方法
在测试类的 main 中创建员工数组,通过键盘输入员工对象信息并遍历输出
package Homework1;import java.util.Scanner;
public class Test {public static void main(String[] args) {Scanner sc = new Scanner(System.in);Employee[] employees = new Employee[3];System.out.println("--------------------------------开始添加--------------------------------");for (int i = 0; i < employees.length; i++) {System.out.println("第" + (i + 1) + "个员工----------------------------------------------------------");System.out.print("姓名:");String name = sc.next();System.out.print("性别:");char gender = sc.next().charAt(0);System.out.print("年龄:");int age = sc.nextInt();System.out.print("工资:");double salary = sc.nextDouble();System.out.print("电话:");String phone = sc.next();System.out.print("邮箱:");String email = sc.next();Employee employee = new Employee();employee.setName(name);employee.setGender(gender);employee.setAge(age);employee.setSalary(salary);employee.setPhone(phone);employee.setEmail(email);employees[i] = employee;}System.out.println("--------------------------------添加完成--------------------------------");System.out.println("--------------------------------开始显示--------------------------------");System.out.println("编号\t姓名\t性别\t年龄\t工资\t\t电话\t\t邮箱");for (int i = 0; i < employees.length; i++) {System.out.println((i + 1) + "\t\t" + employees[i].getInfo());}System.out.println("--------------------------------显示完成--------------------------------");}
}class Employee {private String name;private char gender;private int age;private double salary;private String phone;private String email;public String getName() {return name;}public char getGender() {return gender;}public int getAge() {return age;}public double getSalary() {return salary;}public String getPhone() {return phone;}public String getEmail() {return email;}public void setName(String name) {this.name = name;}public void setGender(char gender) {this.gender = gender;}public void setAge(int age) {this.age = age;}public void setSalary(double salary) {this.salary = salary;}public void setPhone(String phone) {this.phone = phone;}public void setEmail(String email) {this.email = email;}String getInfo(){return name + "\t" + gender + "\t\t" + age + "\t\t" + salary + "\t\t" + phone + "\t" + email;}
}
男人女人类
在父类 Person 类中,包含:
1.私有属性:姓名,年龄,职业
2.方法:
1)public void eat():打印xx吃饭
2)public void toilet():打印xx上洗手间
3)public String getInfo():返回姓名、年龄和职业
在男人 Man 类中,包含:
1.重写 eat():xx狼吞虎牙的吃饭
2.增加 public void smoke():打印xx抽烟
在女人 Woman 类中,包含:
1.重写 eat():xx细嚼慢咽的吃饭
2.增加 public void makeup():打印xx化妆
周末一群男男女女相亲,在测试类中创建不同对象并放入 Person[] 数组:
1.遍历数组,自我介绍
2.遍历数组,都去吃饭
3.遍历数组,都上洗手间,男的上完洗手间都去抽烟,女的上完洗手间都去化妆
package Homework2;public class Test {public static void main(String[] args) {Person[] people = new Person[4];people[0] = new Man();people[0].setName("张三");people[0].setAge(23);people[0].setJob("律师");people[1] = new Man();people[1].setName("李四");people[1].setAge(25);people[1].setJob("医生");people[2] = new Woman();people[2].setName("王五");people[2].setAge(22);people[2].setJob("教师");people[3] = new Woman();people[3].setName("赵六");people[3].setAge(24);people[3].setJob("警察");System.out.println("--------------------开始介绍--------------------");for (int i = 0; i < people.length; i++) {System.out.println(people[i].getInfo());}System.out.println("--------------------开始吃饭--------------------");for (int i = 0; i < people.length; i++) {people[i].eat();}System.out.println("--------------------饭后休息--------------------");for (int i = 0; i < people.length; i++) {people[i].toilet();if (people[i] instanceof Man) {Man man = (Man) people[i];man.smoke();}else if(people[i] instanceof Woman) {Woman woman = (Woman) people[i];woman.makeup();}}}
}class Person {private String name;private int age;private String job;public String getName() {return name;}public int getAge() {return age;}public String getJob() {return job;}public void setName(String name) {this.name = name;}public void setAge(int age) {this.age = age;}public void setJob(String job) {this.job = job;}public void eat(){System.out.println(name + "吃饭");}public void toilet(){System.out.println(name + "上洗手间");}public String getInfo(){return "姓名:" + name + ",年龄:" + age + ",职业:" + job;}
}class Man extends Person {@Overridepublic void eat() {System.out.println(getName() + "狼吞虎咽的吃饭");}public void smoke(){System.out.println(getName() + "抽烟");}
}class Woman extends Person {@Overridepublic void eat() {System.out.println(getName() + "细嚼慢咽的吃饭");}public void makeup(){System.out.println(getName() + "化妆");}
}
普通员工、程序员、设计师、架构师
普通员工 Employee 类
1.提供私有属性:编号,姓名,年龄,工资
2.提供 get/set 方法
3.提供 String say() 方法:返回员工的基本信息
4.提供 String getInfo() 方法:返回员工的基本信息
程序员 Programmer 类,继承普通员工类
1.重写 String getInfo() 方法,增加职位“程序员”信息
设计师 Designer 类,继承程序员类
1.增加奖金属性
2.重写 String getInfo() 方法,增加职位“设计师”和奖金信息
架构师 Architect 类,继承设计师类
1.增加股票属性
2.重写 String getInfo() 方法,增加职位“架构师”和奖金、股票信息
在测试类中创建员工数组,并存储1个普通员工对象,2个程序员对象,1个设计师对象,1个架构师对象
package Homework3;public class Test {public static void main(String[] args) {Employee e1 = new Employee();e1.setId(1);e1.setName("段誉");e1.setAge(22);e1.setSalary(3000);Architect a1 = new Architect();a1.setId(2);a1.setName("令狐冲");a1.setAge(32);a1.setSalary(18000);a1.setBonus(15000);a1.setStock(2000);Programmer p1 = new Programmer();p1.setId(3);p1.setName("任我行");p1.setAge(23);p1.setSalary(7000);Programmer p2 = new Programmer();p2.setId(4);p2.setName("张三丰");p2.setAge(24);p2.setSalary(7300);Designer d1 = new Designer();d1.setId(5);d1.setName("周芷若");d1.setAge(28);d1.setSalary(10000);d1.setBonus(5000);Employee[] employees = new Employee[5];employees[0] = e1;employees[1] = a1;employees[2] = p1;employees[3] = p2;employees[4] = d1;System.out.println("------------------------员工信息管理------------------------");System.out.println("编号\t姓名\t年龄\t工资\t\t职位\t奖金\t股票");for (int i = 0; i < employees.length; i++) {System.out.println(employees[i].getInfo());}System.out.println("-----------------------------------------------------------");}
}class Employee {private int id;private String name;private int age;private double salary;public int getId() {return id;}public String getName() {return name;}public int getAge() {return age;}public double getSalary() {return salary;}public void setId(int id) {this.id = id;}public void setName(String name) {this.name = name;}public void setAge(int age) {this.age = age;}public void setSalary(double salary) {this.salary = salary;}public String say(){return id + "\t\t" + name + "\t" + age + "\t\t" + salary;}public String getInfo() {return say();}
}class Programmer extends Employee{@Overridepublic String getInfo() {return super.say() + "\t\t程序员" ;}
}class Designer extends Programmer {private double bonus;public double getBonus() {return bonus;}public void setBonus(double bonus) {this.bonus = bonus;}@Overridepublic String getInfo() {return super.say() + "\t\t设计师\t" + bonus;}
}class Architect extends Designer {private int stock;public int getStock() {return stock;}public void setStock(int stock) {this.stock = stock;}@Overridepublic String getInfo() {return super.say() + "\t\t架构师\t" + getBonus() + "\t" + stock;}
}
day10
普通员工类
1.声明员工类 Employee:
1)包含属性:姓名,性别,年龄,工资,电话,邮箱
2)提供 String getInfo() 方法
2.在测试类的 main 中创建员工数组,输入员工对象信息并遍历输出
package Homework1;import java.util.Scanner;
public class Test {public static void main(String[] args) {Scanner sc = new Scanner(System.in);Employee[] employees = new Employee[3];for (int i = 0; i < employees.length; i++) {System.out.println("---------------------------添加第" + (i + 1) + "个员工--------------------------");System.out.print("姓名:");String name = sc.next();System.out.print("性别:");char gender = sc.next().charAt(0);System.out.print("年龄:");int age = sc.nextInt();System.out.print("工资:");double salary = sc.nextDouble();System.out.print("电话:");String phone = sc.next();System.out.print("邮箱:");String email = sc.next();employees[i] = new Employee(name, gender, age, salary, phone, email);}System.out.println("-----------------------------添加完成-----------------------------");System.out.println("---------------------------展示员工列表---------------------------");System.out.println("编号\t姓名\t性别\t年龄\t工资\t\t电话\t\t邮箱");for (int i = 0; i < employees.length; i++) {System.out.println((i + 1) + "\t\t" + employees[i].getInfo());}System.out.println("-----------------------------展示完成-----------------------------");}
}class Employee {private String name;private char gender;private int age;private double salary;private String phone;private String email;public Employee() {}public Employee(String name, char gender, int age, double salary, String phone, String email) {this.name = name;this.gender = gender;this.age = age;this.salary = salary;this.phone = phone;this.email = email;}public String getName() {return name;}public void setName(String name) {this.name = name;}public char getGender() {return gender;}public void setGender(char gender) {this.gender = gender;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public double getSalary() {return salary;}public void setSalary(double salary) {this.salary = salary;}public String getPhone() {return phone;}public void setPhone(String phone) {this.phone = phone;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}public String getInfo() {return name + "\t" + gender + "\t\t" + age + "\t\t" + salary + "\t\t" + phone + "\t" + email;}
}
男人女人类
1.在父类 Person 类中:
1)私有属性:姓名,年龄,职业
2)public void eat():打印xx吃饭
3)public void toilet():打印xx上洗手间
4)public String getInfo():返回姓名、年龄和职业信息
2.在子类 Man 类中:
1)重写 eat():xx狼吞虎牙的吃饭
2)增加 public void smoke() :打印xx抽烟
3.在子类 Woman 类中:
1)重写 eat():xx细嚼慢咽的吃饭
2)增加 public void makeup():打印xx化妆
4.周末一堆男男女女相亲,在测试类的 main 中创建不同对象并放入 Person[] 数组:
1)遍历数组,开始介绍
2)遍历数组,开始吃饭
3)遍历数组,开始上洗手间,男的上完洗手间开始抽烟,女的上完洗手间开始化妆
package Homework2;public class Test {public static void main(String[] args) {Person[] people = new Person[4];people[0] = new Man("张三", 27, "警察");people[1] = new Man("李四", 29, "医生");people[2] = new Woman("赵六", 26, "律师");people[3] = new Woman("齐七", 24, "经纪人");System.out.println("------------------开始介绍------------------");for (int i = 0; i < people.length; i++) {System.out.println(people[i].getInfo());}System.out.println("------------------开始吃饭------------------");for (int i = 0; i < people.length; i++) {people[i].eat();}System.out.println("------------------开始活动------------------");for (int i = 0; i < people.length; i++) {people[i].toilet();if(people[i] instanceof Man) {Man man = (Man) people[i];man.smoke();}else {Woman woman = (Woman) people[i];woman.makeup();}}}
}class Person {private String name;private int age;private String work;public Person(String name, int age, String work) {this.name = name;this.age = age;this.work = work;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getWork() {return work;}public void setWork(String work) {this.work = work;}public void eat() {System.out.println(name + "吃饭");}public void toilet() {System.out.println(name + "上洗手间");}public String getInfo() {return "姓名:" + name + ",年龄:" + age + ",职业:" + work;}
}class Man extends Person {public Man(String name, int age, String work) {super(name, age, work);}@Overridepublic void eat() {System.out.println(getName() + "狼吞虎咽的吃饭");}public void smoke() {System.out.println(getName() + "抽烟");}
}class Woman extends Person {public Woman(String name, int age, String work) {super(name, age, work);}@Overridepublic void eat() {System.out.println(getName() + "细嚼慢咽的吃饭");}public void makeup() {System.out.println(getName() + "化妆");}
}
普通员工、程序员、设计师、架构师
1.普通员工 Employee 类
1)提供属性:编号,姓名,年龄,工资
2)提供 String say() 方法:返回员工的基本信息
3)提供 String getInfo() 方法:返回员工的基本信息
2.程序员 Programmer 类,继承普通员工类:
1)重写 String getInfo() 方法,增加职位“程序员”信息
3.设计师 Designer 类,继承程序员类:
1)增加奖金属性
2)重写 String getInfo() 方法,增加职位“设计师”和奖金信息
4.架构师 Architect 类,继承设计师类:
1)增加股票属性
2)重写 String getInfo() 方法,增加职位“架构师”和奖金、股票信息
5.在测试类中创建员工数组,并存储1个普通员工对象,1个设计师对象,2个程序员对象,1个架构师对象
package Homework3;public class Test {public static void main(String[] args) {Employee[] employees = new Employee[5];employees[0] = new Employee(1, "段誉", 22, 3000);employees[1] = new Architect(2, "令狐冲", 32, 18000, 15000, 2000);employees[2] = new Programmer(3, "任我行", 23, 7000);employees[3] = new Programmer(4, "张三丰", 24, 7300);employees[4] = new Designer(5, "周芷若", 28, 10000, 5000);System.out.println("------------------------员工信息管理------------------------");System.out.println("编号\t姓名\t年龄\t工资\t\t职位\t奖金\t股票");for (int i = 0; i < employees.length; i++) {System.out.println(employees[i].getInfo());}System.out.println("-----------------------------------------------------------");}
}class Employee {private int id;private String name;private int age;private double salary;public Employee() {}public Employee(int id, String name, int age, double salary) {this.id = id;this.name = name;this.age = age;this.salary = salary;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public double getSalary() {return salary;}public void setSalary(double salary) {this.salary = salary;}public String say() {return id + "\t\t" + name + "\t" + age + "\t\t" + salary;}public String getInfo() {return say();}
}class Programmer extends Employee {public Programmer() {}public Programmer(int id, String name, int age, double salary) {super(id, name, age, salary);}@Overridepublic String getInfo() {return super.say() + "\t\t程序员";}
}class Designer extends Programmer {private double bonus;public Designer() {}public Designer(int id, String name, int age, double salary, double bonus) {super(id, name, age, salary);this.bonus = bonus;}public double getBonus() {return bonus;}public void setBonus(double bonus) {this.bonus = bonus;}@Overridepublic String getInfo() {return super.say() + "\t\t设计师\t" + bonus;}
}class Architect extends Designer {private int stock;public Architect() {}public Architect(int id, String name, int age, double salary, double bonus, int stock) {super(id, name, age, salary, bonus);this.stock = stock;}public int getStock() {return stock;}public void setStock(int stock) {this.stock = stock;}@Overridepublic String getInfo() {return super.say() + "\t\t架构师\t" + getBonus() + "\t" + stock;}
}
阅读如下代码
public class Test {public static void main(String[] args) {new HelloB();} }class HelloA {public HelloA() {System.out.println("HelloA");}{System.out.println("I'm A Class");} }class HelloB extends HelloA {public HelloB() {System.out.println("HelloB");}{System.out.println("I'm B Class");} }
public class Test {public static void main(String[] args) {new HelloB();//I'm A Class//HelloA//I'm B Class//HelloB}
}class HelloA {public HelloA() {System.out.println("HelloA");}{System.out.println("I'm A Class");}
}class HelloB extends HelloA {public HelloB() {System.out.println("HelloB");}{System.out.println("I'm B Class");}
}
阅读如下代码
public class Test {public static void main(String[] args) {Father f = new Father();System.out.println("-----------------------");Child c = new Child();} }class Father {public Father() {System.out.println("father");} }class Child extends Father {public Child() {System.out.println("child");} }
public class Test {public static void main(String[] args) {Father f = new Father();//fatherSystem.out.println("-----------------------");Child c = new Child();//father//child}
}class Father {public Father() {System.out.println("father");}
}class Child extends Father {public Child() {System.out.println("child");}
}
实例初始化运行结果分析
public class Test {public static void main(String[] args) {new Child("mike");} }class People {private String name;public People() {System.out.println("1");}public People(String name) {System.out.println("2");this.name = name;} }class Child extends People {People father;public Child(String name) {System.out.println("3");father = new People(name + " F");}public Child() {System.out.println("4");} }
public class Test {public static void main(String[] args) {new Child("mike"); //1, 3, 2}
}class People {private String name;public People() {System.out.println("1");}public People(String name) {System.out.println("2");this.name = name;}
}class Child extends People {People father;public Child(String name) {System.out.println("3");father = new People(name + " F");}public Child() {System.out.println("4");}
}
继承、属性同名问题
public class Test extends Father {private String name = "test";public static void main(String[] args) {Test test = new Test();System.out.println(test.getName());} }class Father {private String name = "father";public String getName() {return name;} }
public class Test extends Father {private String name = "test";public static void main(String[] args) {Test test = new Test();System.out.println(test.getName()); //father}
}class Father {private String name = "father";public String getName() {return name;}
}
实例初始化
public class Test {public static void main(String[] args) {new A(new B());} }class A {public A() {System.out.println("A");}public A(B b) {this();System.out.println("AB");} }class B {public B() {System.out.println("B");} }
public class Test {public static void main(String[] args) {new A(new B()); //3, 1, 2}
}class A {public A() {System.out.println("A"); //1}public A(B b) {this();System.out.println("AB"); //2}
}class B {public B() {System.out.println("B"); //3}
}
继承
public class Test {public static void main(String[] args) {Father f = new Father();Son s = new Son();System.out.println(f.getInfo()); System.out.println(s.getInfo());s.setInfo("尚硅谷");System.out.println(f.getInfo());System.out.println(s.getInfo());} }class Father {private String info = "atguigu";public String getInfo() {return info;}public void setInfo(String info) {this.info = info;} }class Son extends Father { }
public class Test {public static void main(String[] args) {Father f = new Father();Son s = new Son();System.out.println(f.getInfo()); //atguiguSystem.out.println(s.getInfo()); //atguigus.setInfo("尚硅谷");System.out.println(f.getInfo()); //atguiguSystem.out.println(s.getInfo()); //尚硅谷}
}class Father {private String info = "atguigu";public String getInfo() {return info;}public void setInfo(String info) {this.info = info;}
}class Son extends Father {
}
this 和 super
public class Test {public static void main(String[] args) {Father f = new Father();Son s = new Son();System.out.println(f.getInfo()); System.out.println(s.getInfo());s.test();s.setInfo("大硅谷");System.out.println(f.getInfo());System.out.println(s.getInfo());s.test();} }class Father {private String info = "atguigu";public String getInfo() {return info;}public void setInfo(String info) {this.info = info;} }class Son extends Father {private String info = "尚硅谷";public void test() {System.out.println(this.getInfo());System.out.println(super.getInfo());} }
public class Test {public static void main(String[] args) {Father f = new Father();Son s = new Son();System.out.println(f.getInfo()); //atguiguSystem.out.println(s.getInfo()); //atguigus.test(); //atguigu atguigus.setInfo("大硅谷");System.out.println(f.getInfo()); //atguiguSystem.out.println(s.getInfo()); //大硅谷s.test(); //大硅谷 大硅谷}
}class Father {private String info = "atguigu";public String getInfo() {return info;}public void setInfo(String info) {this.info = info;}
}class Son extends Father {private String info = "尚硅谷";public void test() {System.out.println(this.getInfo()); System.out.println(super.getInfo()); }
}
this、super、重写
public class Test {public static void main(String[] args) {Father f = new Father();Son s = new Son();System.out.println(f.getInfo()); System.out.println(s.getInfo());s.test();s.setInfo("大硅谷");System.out.println(f.getInfo());System.out.println(s.getInfo());s.test();} }class Father {private String info = "atguigu";public String getInfo() {return info;}public void setInfo(String info) {this.info = info;} }class Son extends Father {private String info = "尚硅谷";public String getInfo() {return info;}public void setInfo(String info) {this.info = info;}public void test() {System.out.println(this.getInfo());System.out.println(super.getInfo());} }
public class Test {public static void main(String[] args) {Father f = new Father();Son s = new Son();System.out.println(f.getInfo()); //atguiguSystem.out.println(s.getInfo()); //尚硅谷s.test(); //尚硅谷 atguigus.setInfo("大硅谷");System.out.println(f.getInfo()); //atguiguSystem.out.println(s.getInfo()); //大硅谷s.test(); //大硅谷 atguigu}
}class Father {private String info = "atguigu";public String getInfo() {return info;}public void setInfo(String info) {this.info = info;}
}class Son extends Father {private String info = "尚硅谷";public String getInfo() {return info;}public void setInfo(String info) {this.info = info;}public void test() {System.out.println(this.getInfo());System.out.println(super.getInfo());}
}
this
public class Test {public static void main(String[] args) {Father f = new Son();System.out.println("-----------");System.out.println(f.x);} }class Father {int x = 10;public Father() {this.print();x = 20;}public void print() {System.out.println("Father.x = " + x);} }class Son extends Father {int x = 30;public Son() {this.print();x = 40;}public void print() {System.out.println("Son.x = " + x);} }
public class Test {public static void main(String[] args) {Father f = new Son(); //方法重载//Son.x = 0,此时子类的x还没有完成显示初始化//Son.x = 30,此时子类的x已经完成显示初始化System.out.println("-----------");System.out.println(f.x); //属性不重载//20,此时父类构造器已执行完毕}
}class Father {int x = 10;public Father() {this.print();x = 20;}public void print() {System.out.println("Father.x = " + x);}
}class Son extends Father {int x = 30;public Son() {this.print();x = 40;}public void print() {System.out.println("Son.x = " + x);}
}
虚方法
public class Test {public static void main(String[] args) {A a1 = new A();A a2 = new B();B b = new B();C c = new C();D d = new D();System.out.println("(1) " + a1.show(b));System.out.println("(2) " + a2.show(d));System.out.println("(3) " + b.show(c));System.out.println("(4) " + b.show(d));} }class A {public String show(D obj) {return "A and D";}public String show(A obj) {return "A and A";} }class B extends A {public String show(B obj) {return "B and B";}public String show(A obj) {return "B and A";} }class C extends B { }class D extends B { }
public class Test {public static void main(String[] args) {A a1 = new A();A a2 = new B();B b = new B();C c = new C();D d = new D();System.out.println(a1.show(b)); //A and ASystem.out.println(a2.show(d)); //A and DSystem.out.println(b.show(c)); //B and BSystem.out.println(b.show(d)); //A and D}
}class A {public String show(D obj) {return "A and D";}public String show(A obj) {return "A and A";}
}class B extends A {
// @Override
// public String show(D obj) {
// return super.show(obj);
// }public String show(B obj) {return "B and B";}public String show(A obj) {return "B and A";}
}class C extends B {
}class D extends B {
}
虚方法
public class Test {public static void main(String[] args) {A a1 = new A();A a2 = new B();B b = new B();C c = new C();D d = new D();System.out.println(a1.show(b));System.out.println(a2.show(d));System.out.println(b.show(c));System.out.println(b.show(d));} }class A {public String show(C obj) {return "A and C";}public String show(A obj) {return "A and A";} }class B extends A {public String show(B obj) {return "B and B";}public String show(A obj) {return "B and A";} }class C extends B { }class D extends B { }
public class Test {public static void main(String[] args) {A a1 = new A();A a2 = new B();B b = new B();C c = new C();D d = new D();System.out.println("(1) " + a1.show(b)); //(1) A and ASystem.out.println("(2) " + a2.show(d)); //(2) A and A?System.out.println("(3) " + b.show(c)); //(3) A and CSystem.out.println("(4) " + b.show(d)); //(4) B and B}
}class A {public String show(C obj) {return "A and C";}public String show(A obj) {return "A and A";}
}class B extends A {public String show(B obj) {return "B and B";}public String show(A obj) {return "B and A";}
}class C extends B {
}class D extends B {
}
多态引用
public class Test {public static void main(String[] args) {Base b = new Sub();System.out.println(b.x); } }class Base {int x = 1; }class Sub extends Base {int x = 2; }
public class Test {public static void main(String[] args) {Base b = new Sub();System.out.println(b.x); //1}
}class Base {int x = 1;
}class Sub extends Base {int x = 2;
}
day11
阅读如下代码,分析运行结果
class HelloA {public HelloA() {System.out.println("HelloA");}{System.out.println("I'm A Class");}static {System.out.println("static A");} }public class HelloB extends HelloA {public HelloB() {System.out.println("HelloB");}{System.out.println("I'm B Class");}static {System.out.println("static B");}public static void main(String[] args) {new HelloB();} }
class HelloA {public HelloA() {System.out.println("HelloA");}{System.out.println("I'm A Class");}static {System.out.println("static A");}
}public class HelloB extends HelloA {public HelloB() {System.out.println("HelloB");}{System.out.println("I'm B Class");}static {System.out.println("static B");}public static void main(String[] args) {new HelloB();//static A//static B//I'm A Class//HelloA//I'm B Class//HelloB}
}
阅读如下代码,分析运行结果
public class Test {public static void main(String[] args) {Son son = new Son();} }class Father {static {System.out.println("1.父类的静态代码块");}{System.out.println("2.父类的非静态代码块");}Father() {System.out.println("3.父类的无参构造");} }class Son extends Father {static {System.out.println("4.子类的静态代码块");}{System.out.println("5.子类的非静态代码块");}Son() {System.out.println("6.子类的无参构造");} }
public class Test {public static void main(String[] args) {Son son = new Son();//1.父类的静态代码块//4.子类的静态代码块//2.父类的非静态代码块//3.父类的无参构造//5.子类的非静态代码块//6.子类的无参构造}
}class Father {static {System.out.println("1.父类的静态代码块");}{System.out.println("2.父类的非静态代码块");}Father() {System.out.println("3.父类的无参构造");}
}class Son extends Father {static {System.out.println("4.子类的静态代码块");}{System.out.println("5.子类的非静态代码块");}Son() {System.out.println("6.子类的无参构造");}
}
数组工具类
声明一个数组工具类 ArrayTools,包含如下方法:
1.public static int binarySearch(int[] arr, int value):使用二分查找法在 arr 数组中查找 value 的下标,如果 value 不存在,则返回-1,如果数组 arr 不是有序的,结果将不一定正确
2.public static int[] copyOf(int[] arr, int newLength):复制一个 newLength 长的数组,如果 newLength <= arr.length,则新数组复制 arr 数组的 [0, newLength - 1] 的元素,如果 newLength <= arr.length,则新数组前面 [0, newLength - 1] 的元素从 arr 数组复制,后面的元素保持默认值
3.public static void sort(int[] arr):用冒泡排序实现 arr 数组从小到大排序
4.public static String toString(int[] arr):将元素拼接为“{元素1, 元素2, ......}”的字符串返回
在测试类的 main 方法中:
1.随机产生10个 [0, 100) 的元素然后遍历显示
2.从小到大排序后显示
3.从键盘输入一个整数,查找它是否在排序后的数组中,如果存在就显示下标,如果不存在就提示不存在
4.复制3个数组,新数组的长度分别为5、10和15,然后遍历显示新数组
package Homework3;import java.util.Scanner;public class Test {public static void main(String[] args) {int[] arr = new int[10];for (int i = 0; i < arr.length; i++) {arr[i] = (int) (Math.random() * 100);}System.out.println("数组:" + ArrayTools.toString(arr));ArrayTools.sort(arr);System.out.println("将数组从小到大排序:" + ArrayTools.toString(arr));Scanner sc = new Scanner(System.in);System.out.println("请输入一个整数:");int value = sc.nextInt();int index = ArrayTools.binarySearch(arr, value);if(index != -1) {System.out.println(value + "在数组中的下标:" + index);}else {System.out.println(value + "在数组中不存在");}int[] newArr1 = ArrayTools.copyOf(arr, 5);int[] newArr2 = ArrayTools.copyOf(arr, 10);int[] newArr3 = ArrayTools.copyOf(arr, 15);System.out.println("新数组1:" + ArrayTools.toString(newArr1));System.out.println("新数组2:" + ArrayTools.toString(newArr2));System.out.println("新数组3:" + ArrayTools.toString(newArr3));}
}class ArrayTools {public static int binarySearch(int[] arr, int value) {for (int left = 0, right = arr.length - 1; left <= right; ) {int mid = left + (right - left) / 2;if(value > arr[mid]) {left = mid + 1;}else if(value < arr[mid]) {right = mid - 1;}else {return mid;}}return -1;}public static int[] copyOf(int[] arr, int newLength) {int[] newArr = new int[newLength];for (int i = 0; i < newArr.length && i < arr.length; i++) {newArr[i] = arr[i];}return newArr;}public static void sort(int[] arr) {for (int i = 0; i < arr.length - 1; i++) {for (int j = 0; j < arr.length - 1 - i; j++) {if(arr[j] > arr[j + 1]) {int temp = arr[j + 1];arr[j + 1] = arr[j];arr[j] = temp;}}}}public static String toString(int[] arr) {String s = "{";for (int i = 0; i < arr.length; i++) {if(i != arr.length - 1) {s += arr[i] + ",";}else {s += arr[i];}}s += "}";return s;}
}
阅读代码,分析运行结果
public class Test {public static void main(String[] args) {Integer i1 = 128;Integer i2 = 128;int i3 = 128;int i4 = 128;System.out.println(i1 == i2);System.out.println(i3 == i4);System.out.println(i1 == i3);} }
阅读代码,分析运行结果
public class Test {public static void main(String[] args) {double a = 2.0;double b = 2.0;Double c = 2.0;Double d = 2.0;System.out.println(a == b);System.out.println(c == d);System.out.println(a == d);} }
颜色枚举类
声明颜色枚举类 Color:
1.声明 final 修饰的 int 类型的属性 red、green 和 blue
2.声明 final 修饰的 String 类型的属性 description
3.声明有参构造 Color(int red, int green, int blue, String description)
4.创建7个常量对象:赤、橙、黄、绿、青、蓝、紫
5.重写 toString 方法,例如:RED(255, 0, 0) -> 红色
在测试类中,使用枚举类,获取绿色对象,并打印对象
7个常量对象的 RGB 值如下:
赤(RED):(255, 0, 0)
橙(ORANGE):(255, 1280, 0)
黄(YELLOW):(255, 255, 0)
绿(GREEN):(0, 255, 0)
青(CYAN):(0, 255, 255)
蓝(BLUE):(0, 0, 255)
紫(PURPLE):(128, 0, 255)
设备状态枚举类
声明设备状态枚举类 Status:
1.声明 final 修饰的 String 类型的属性 description 和 int 类型的属性 value,value 值初始化为 ordinal() 的值
2.声明有参构造 Status(String description)
3.重写 toString 方法,返回 description 值
4.提供静态方法 public static Status getByValue(int value),根据 value 值获取 Status 状态对象
5.创建3个常量对象:
FREE("空闲"), USED("在用"), SCRAP("报废")
声明设备类型 Equipment:
1.声明私有化属性:int 类型的设备编号,String 类型的设备品牌,double 类型的价格,String 类型的设备名称,Status 类型的状态
2.提供无参和有参构造
3.重写 toString 方法
现有 Data.java,代码如下:
public class Data {public static final String[][] EQUIPMENTS = {{"1", "联想", "6000", "拯救者", "0"},{"2", "宏碁", "5000", "AT7-N52", "0"},{"3", "小米", "2000", "5V5Pro", "1"},{"4", "戴尔", "4000", "3800-R33", "1"},{"5", "苹果", "12000", "MBP15", "1"},{"6", "华硕", "8000", "K30BD-21寸", "2"},{"7", "联想", "7000", "YOGA", "0"},{"8", "惠普", "5800", "X500", "2"},{"9", "苹果", "4500", "2021Pro", "0"},{"10", "惠普", "5800", "FZ5", "1"}}; }
在测试类中,创建 Equipment 类型的数组,使用 Data 类型的二维数组 EQUIPMENTS 的信息初始化设备对象,并遍历输出
阅读以下代码,分析运行结果
public class Test {public static void main(String[] args) {Zi zi = new Zi();} }class Fu {private static int i = getNum("i");private int j = getNum("j");static {print("父类静态代码块");}{print("父类非静态代码块,又称为构造代码块");}Fu() {print("父类构造器");}public static void print(String str) {System.out.println(str + "->" + i);}public static int getNum(String str) {print(str);return ++i;} }class Zi extends Fu {private static int k = getNum("k");private int h = getNum("h");static {print("子类静态代码块");}{print("子类非静态代码块,又称为构造代码块");}Zi() {print("子类构造器");}public static void print(String str) {System.out.println(str + "->" + k);}public static int getNum(String str) {print(str);return ++k;} }
阅读以下代码,分析运行结果
public class Test {public static int k = 0;public static Test t1 = new Test("t1");public static Test t2 = new Test("t2");public static int i = print("i");public static int n = 99;public int j = print("j");{print("构造块");}static{print("静态块");}public Test(String str){System.out.println((++k) + ":" + str + " i=" + i + " n=" + n); ++n; ++i; }public static int print(String str){System.out.println((++k) + ":" + str + " i=" + i + " n=" + n); ++n; return ++i; }public static void main(String[] args) {} }
day12
交通工具
1.声明抽象类 Vehicle 交通工具:
1)包含 int 类型的私有属性 wheels
2)包含有参构造 Vehicle(int wheels)
3)包含 get/set 方法
4)包含抽象方法 public abstract void drive()
5)重写 toString()
2.声明子类 Monocyle 单轮车:重写抽象方法 drive,输出“脚踏单轮车,摇摇摆摆往前走”
3.声明子类 Bicycle 自行车:重写抽象方法 drive,输出“脚踏双轮车,悠哉悠哉往前走”
4.声明子类 Tricycle 三轮车: 重写抽象方法 drive,输出“脚踏三轮车,稳稳当当往前走”
5.测试类:创建数组并添加对象,打印对象并调用 drive 方法
package Homework1;public class Test {public static void main(String[] args) {Vehicle[] vehicles = new Vehicle[3];vehicles[0] = new Monocycle(1);vehicles[1] = new Bicycle(2);vehicles[2] = new Tricycle(3);for (int i = 0; i < vehicles.length; i++) {System.out.println(vehicles[i]);vehicles[i].drive();}}
}abstract class Vehicle {private int wheels;public Vehicle(int wheels) {this.wheels = wheels;}public int getWheels() {return wheels;}public void setWheels(int wheels) {this.wheels = wheels;}public abstract void drive();@Overridepublic String toString() {return "Vehicle{" +"wheels=" + wheels +'}';}
}class Monocycle extends Vehicle {public Monocycle(int wheels) {super(wheels);}@Overridepublic void drive() {System.out.println("脚踏单轮车,摇摇摆摆往前走");}
}class Bicycle extends Vehicle {public Bicycle(int wheels) {super(wheels);}@Overridepublic void drive() {System.out.println("脚踏双轮车,悠哉悠哉往前走");}
}class Tricycle extends Vehicle {public Tricycle(int wheels) {super(wheels);}@Overridepublic void drive() {System.out.println("脚踏三轮车,稳稳当当往前走");}
}
支付接口
1.声明可支付接口 Payable:包含抽象方法 void pay()
2.声明支付枚举类 Payment:
1)声明 String类型的 final 属性 description
2)声明有参构造 Payment(String description)
3)重写 toString 方法,返回 description
ALIPAY("支付宝"), WECHAT("微信"), CREDITCARD("信用卡"), DEPOSITCARD("储蓄卡")
4)枚举类 Payment 实现接口 Payable:
支付宝/微信:对接口的实现是打印“扫码支付”
信用卡/储蓄卡:对接口的实现是打印“输入卡号支付”
3.在测试类中,获取所有支付对象,打印支付对象并调用它们的 pay() 方法
各种鸟
1.声明 Flybale 接口:包含抽象方法 void fly()
2.声明 Swimming 接口:包含抽象方法 void swim()
3.声明父类 Bird:包含抽象方法 public abstract void eat()
4.声明子类 Penguin 企鹅:
1)继承 Bird 类,重写 eat 方法,输出“企鹅吃南极磷虾”
2)实现 Swimming 接口,重写 swim 方法,输出“企鹅下海捉虾”
5.声明子类 Swan 天鹅:
1)继承 Bird 类,重写 eat 方法,输出“天鹅吃水生植物的根茎和种子、水生昆虫、螺类和小鱼”
2)实现 Flyable 接口,重写 fly 方法,输出“天鹅展翅高飞,天南海北任我游”
3)实现 Swimming 接口,重写 swim() 方法,输出“天鹅把羽毛洗的锃亮,顺便捉条鱼”
6.声明子类 chicken 鸡:
1)继承 Bird 类,重写 eat 方法,输出“鸡吃谷子”
2)实现 Flyable 接口,重写 fly 方法,输出“鸡上房揭瓦,满院子乱扑腾”
7.测试类:
1)创建 Bird 数组,并把 Penguins 企鹅、Swan 天鹅、Chicken 鸡的对象放到 Bird 数组中,遍历数组
2)调用各个元素的 eat 方法
3)会飞的调用 fly 方法(提示:可以使用 instanceof 判断)
4)会游的调用 swim 方法
package Homework3;public class Test {public static void main(String[] args) {Bird[] birds = new Bird[3];birds[0] = new Penguin();birds[1] = new Swan();birds[2] = new Chicken();for (int i = 0; i < birds.length; i++) {birds[i].eat();if(birds[i] instanceof Flyable) {Flyable flyable = (Flyable) birds[i];flyable.fly();}if (birds[i] instanceof Swimming) {Swimming swimming = (Swimming) birds[i];swimming.swim();}}//企鹅吃南极磷虾//企鹅下海捉虾//天鹅吃水生植物的根茎和种子、水生昆虫、螺类和小鱼//天鹅展翅高飞,天南海北任我游//天鹅把羽毛洗的锃亮,顺便捉条鱼//鸡吃谷子//鸡上房揭瓦,满院子乱扑腾}
}interface Flyable {void fly();
}interface Swimming {void swim();
}abstract class Bird {public abstract void eat();
}class Penguin extends Bird implements Swimming {@Overridepublic void eat() {System.out.println("企鹅吃南极磷虾");}@Overridepublic void swim() {System.out.println("企鹅下海捉虾");}
}class Swan extends Bird implements Flyable, Swimming {@Overridepublic void eat() {System.out.println("天鹅吃水生植物的根茎和种子、水生昆虫、螺类和小鱼");}@Overridepublic void fly() {System.out.println("天鹅展翅高飞,天南海北任我游");}@Overridepublic void swim() {System.out.println("天鹅把羽毛洗的锃亮,顺便捉条鱼");}
}class Chicken extends Bird implements Flyable {@Overridepublic void eat() {System.out.println("鸡吃谷子");}@Overridepublic void fly() {System.out.println("鸡上房揭瓦,满院子乱扑腾");}
}
尚硅谷
1.编写一个匿名内部类,它继承 Object,并在匿名内部类中,声明一个方法 public void print(),输出“尚硅谷”
2.请编写代码调用这个方法
public class Test1 {public static void main(String[] args) {new Object() {public void print() {System.out.println("尚硅谷");}}.print();}
}
我爱尚硅谷/尚硅谷爱我
1.已知 java.lang 包下有一个 Thread 类(这个类不用写),该类有:
1)public Thread(String name) 构造器
2)public Thread(Runnable target) 构造器
3)public void run() 方法
4)public void start() 方法
5)public String getName() 方法
2.已知 java.lang 包下还有一个 Runnable 接口(这个接口不用写),该接口:抽象方法 public void run()
3.测试类:
1)请用匿名内部类的方法继承 Thread 类,并显示使用 Thread(String name) 构造器,传入实参“自己的姓名”,在匿名内部类中重写 run 方法,输出“xx爱尚硅谷”,其中xx通过 getName() 方法获取,同时调用 Thread 类匿名子类对象的 start() 方法
2)请用 Thread(Runnable target) 构造器创建 Thread 类的对象,并且用匿名内部类的方法实现 Runnable 接口,重写 run 方法,输出“尚硅谷爱我”,调用 Thread 类对象的 start 方法
3)运行测试类,查看运行效果
public class Test2 {public static void main(String[] args) {new Thread("张三") {@Overridepublic void run() {System.out.println(getName() + "爱尚硅谷");}}.start();new Thread(new Runnable() {@Overridepublic void run() {System.out.println("尚硅谷爱我");}}).start();}
}
阅读代码,分析运行结果
public class Test {public static void main(String[] args) {Out.In in = new Out().new In();in.print();} }class Out {private int a = 12;class In {private int a = 13;public void print() {int a = 14;System.out.println("局部变量:" + a);System.out.println("内部类变量:" + this.a);System.out.println("外部类变量:" + Out.this.a);}} }
public class Test {public static void main(String[] args) {Out.In in = new Out().new In();in.print();//局部变量:14//内部类变量:13//外部类变量:12}
}class Out {private int a = 12;class In {private int a = 13;public void print() {int a = 14;System.out.println("局部变量:" + a);System.out.println("内部类变量:" + this.a);System.out.println("外部类变量:" + Out.this.a);}}
}
阅读代码,分析运行结果
public class Test {public static void main(String[] args) {Out out = new Out();out.print(3);} }class Out {private int a = 12;public void print(final int x) {class In {public void inPrint() {System.out.println(x);System.out.println(a);}}new In().inPrint();} }
public class Test {public static void main(String[] args) {Out out = new Out();out.print(3);//3//12}
}class Out {private int a = 12;public void print(final int x) {class In {public void inPrint() {System.out.println(x);System.out.println(a);}}new In().inPrint();}
}
员工筛选
1.已知在 java.util.function 包下有一个 Predicate 接口(这个接口不用写):包含抽象方法 boolean test(Object obj)
2.声明一个数组工具类 ArrayTool:包含静态方法 public static void print(Object[] arr) ,使用 foreach 循环遍历输出数组元素
3.声明一个员工类 Employee:
1)包含私有化属性:编号、姓名、年龄、薪资
2)提供无参和有参构造
3)提供 get/set 方法
4)重写 toString 方法,返回员工对象的基本信息
4.声明一个员工管理类 EmployeeService:
1)包含 private Employee[] arr 并创建长度为5的数组
2)包含 private int total,记录 arr 中员工对象个数
3)包含 public void add(Employee emp) 方法,将 emp 对象添加到 arr 数组中
4)包含 public Employee[] get(Predicate p) 方法,这个方法的作用就是在 arr 数组中筛选出满足某个条件的员工对象:
要求遍历 arr 数组,统计 arr 数组中有几个元素通过 p 的 test 方法判断返回 true,假设 count 个
创建 Employee[] 数组 result,长度为 count,并把 arr 中满足 p 的 test 方法条件的元素添加到返回值的 result 数组中
5.在测试类中,创建 EmployeeService 对象:
1)调用 add 方法添加如下员工对象:
new Employee(4, "李四", 24, 24000);
new Employee(3, "张三", 23, 13000);
new Employee(2, "王五", 25, 15000);
new Employee(1, "赵六", 27, 17000);
new Employee(2, "前七", 16, 6000);
2)调用 get(Predicate p)方法。通过匿名内部类的对象给形参 p 赋值,分别实现获取:
所有员工对象
所有年龄超过25的员工
所有薪资高于15000的员工
所有年龄超过25且薪资高于15000的员工
分别遍历输出
动态数组
1.已知 java.lang 包有一个 Iterable 接口(这个接口不用写),实现该接口类型的对象,就支持 foreach 循环遍历,Interable 接口包含:抽象方法 Iterator iterator()
2.已知 java.util 包下有一个 Iterator 接口(这个接口不用写),Iterator 接口包含抽象方法:
1)boolean hasNext()
2)Object next()
3.声明一个动态数组类型 MyArrayList,当做容器类使用,模拟动态数组数据结构的容器:
1)包含私有属性:
Object[] all:用于保存对象,初始化长度为10
int total:记录实际存储的对象个数
2)包含方法:
public void add(Object element):用于添加一个元素到当前容器中,如果数组 all 已满,不添加
public void remove(int index):如果 index<0 或 index>=total,就打印“没有这个元素”并返回,否则就替换 index 位置的元素为 value
public void set(int index, Object value):如果 index<0 或 index>=total 就打印“没有这个元素”并返回,否则就替换 index 位置的元素为 value
public Object get(int index):如果 index<0 或 index>=total 就打印“没有这个元素”并返回 null,否则返回 index 位置的元素
让类 MyArrayList 实现 Iterable 接口,并重写 Iterable ierable() 方法,返回内部类 Itr 的对象
4.在类 MyArrayList 内部中声明 private 的非静态内部类 Itr,实现 Iterator 接口:
1)声明属性:int cursor(游标)
2)抽象方法 boolean hasNext() 实现为 return cursor != total
3)抽象方法 Object next() 实现为 return all[cursor++]
5.在测试类中:
1)创建 MyArrayList 的对象 list
2)调用 list 的 add 方法,连续添加5个对象,分别为“atguigu”,“java”,“bigdata”,“h5”,“ui”,并用 foreach 遍历输出
3)调用 list 的 set 方法,替换[1]的对象为“javaee”,并用 foreach 遍历输出
4)调用 list 的 remove 方法,删除[1]的对象,并用 foreach 遍历输出
5)调用 list 的 get 方法,获取[1]的对象
6)调用 list 的 iterator 方法,获取 Iterator 接口的实现类对象,结合 while 循环调用 hasNext() 和 next() 遍历容器中的所有对象
day13
阅读代码,分析运行结果
public class Test1 {public static void main(String[] args) {try {return;} finally {System.out.println("finally");}} }
public class Test01 {public static void main(String[] args) {try {return;} finally {System.out.println("finally");}}//finally
}
阅读代码,分析运行结果
public class Test02 {{System.out.println("a");}static {System.out.println("b");}Test02() {System.out.println("c");}public static String getOut() {try {return "1";}catch (Exception e) {return "2";} finally {return "3";}}public static void main(String[] args) {System.out.println(getOut());} }
public class Test02 {{System.out.println("a");}static {System.out.println("b");}Test02() {System.out.println("c");}public static String getOut() {try {return "1";}catch (Exception e) {return "2";} finally {return "3";}}public static void main(String[] args) {System.out.println(getOut());//b//3}
}
阅读代码,分析运行结果
import java.io.IOException;public class Test03 {public static void main(String[] args) {int a = -1;try {if(a > 0) {throw new RuntimeException("");}else if(a < 0) {throw new IOException("");}else {return;}}catch (IOException e) {System.out.println("IOException");}catch (Throwable e) {System.out.println("Throwable");}finally {System.out.println("finally");}}
}
import java.io.IOException;public class Test03 {public static void main(String[] args) {int a = -1;try {if(a > 0) {throw new RuntimeException("");}else if(a < 0) {throw new IOException("");}else {return;}}catch (IOException e) {System.out.println("IOException"); //IOException}catch (Throwable e) {System.out.println("Throwable"); }finally {System.out.println("finally"); //finally}}
}
阅读代码,分析运行结果
public class Test04 {public static int fun() {int result = 5;try {result = result / 0;return result;}catch (Exception e) {System.out.println("Exception");result = -1;return result;}finally {result = 10;System.out.println("finally");}}public static void main(String[] args) {int x = fun();System.out.println(x);} }
public class Test04 {public static int fun() {int result = 5;try {result = result / 0;return result;}catch (Exception e) {System.out.println("Exception"); //Exceptionresult = -1;return result; //return -1}finally {result = 10;System.out.println("finally"); //finally}}public static void main(String[] args) {int x = fun(); System.out.println(x); //-1}
}
阅读代码,分析运行结果
public class Test05 {public static int aMethod(int i) throws Exception {try {return i / 10;}catch (Exception e) {throw new Exception("exception in aMethod");}finally {System.out.println("finally");}}public static void main(String[] args) {try {aMethod(0);} catch (Exception e) {System.out.println("exception in main");}}
}
package Homework5;public class Test05 {public static int aMethod(int i) throws Exception {try {return i / 10; //return 0}catch (Exception e) {throw new Exception("exception in aMethod");}finally {System.out.println("finally"); //finally}}public static void main(String[] args) {try {aMethod(0);} catch (Exception e) {System.out.println("exception in main");}}
}
阅读代码,选择答案
给出下面的不完整的方法:
{success = connect();if(success == -1) {throw new TimedOutException();} }
TimedOutException 不是一个 RuntimeException,下面的哪些声明可以加入第1行完成此方法的声明?
A.public void method()
B.public void method() throws Exception
C.public void method() throws TimedOutException
D.public void method() throw TimedOutException
E.public throw TimedOutException void method()
C
阅读代码,选择答案
getCustomerInfo() 方法如下,try 中可以捕获三种类型的异常,如果在方法运行中产生了一个 IOException,将会输出什么结果?
public void getCustomerInfo() {try {//do something that may cause an Exception} catch (java.io.FileNotFoundException ex) {System.out.println("FileNotFoundException!");} catch (java.io.IOException ex) {System.out.println("IOException!");} catch (java.lang.Exception ex) {System.out.println("Exception!");}
}
A.IOException!
B.IOException!Exception!
C.FileNotFoundException!IOException!
D.FileNotFoundException!IOException!Exception!
A
银行账户类
1.声明银行账户类 Account:
1)包含私有化属性账户和余额,提供无参和有参构造器,提供 get/set 方法(其中 balance 没有 set 方法)
2)包含取款方法 public void withdraw(double money):
当取款金额为负数时,抛出 Exception,异常信息为“越取你余额越多,你想得美!”
当取款金额超过余额时,抛出 Exception,异常信息为“取款金额不足,不支持当前操作!”
3)包含存款方法 public void save(double money):
当取款金额为负数时,抛出 Exception,异常信息为“越存你余额越少,你愿意吗?”
2.编写测试类,创建账号对象,调用取款和存款方法,传入非法参数,发生对应的异常
public class Test1 {public static void main(String[] args) {Account a = new Account("123456789", 2000);// try {
// a.withdraw(-1000);
// } catch (Exception e) {
// System.err.println(e.getMessage());
// } finally {
// System.out.println(a.getBalance());
// }// try {
// a.withdraw(3000);
// } catch (Exception e) {
// System.err.println(e.getMessage());
// } finally {
// System.out.println(a.getBalance());
// }try {a.save(-1000);} catch (Exception e) {System.err.println(e.getMessage());} finally {System.out.println(a.getBalance());}}
}class Account {private String id;private double balance;public Account() {}public Account(String id, double balance) {this.id = id;this.balance = balance;}public String getId() {return id;}public void setId(String id) {this.id = id;}public double getBalance() {return balance;}public void withdraw(double money) throws Exception {if(money < 0) {throw new Exception("越取你余额越多,你想得美!");}else if(money > balance) {throw new Exception("取款金额不足,不支持当前操作!");}else {balance -= money;}}public void save(double money) throws Exception {if(money < 0) {throw new Exception("越存你余额越少,你愿意吗?");}else {balance += money;}}
}
游戏角色
在一款角色扮演游戏中,每个人都有名字和生命值,角色的生命值不能为负数
要求:当一个人物的生命值为负数时,需要抛出自定义的异常
操作步骤描述:
1.自定义异常类 NoLifeValueException 继承 RuntimeException
2.定义 Person 类
1)属性:名称(name)和生命值(lifeValue)
2)提供无参和有参构造器
4)提供 get/set 方法:
在 setLifevalue(int lifeValue) 方法中,如果 lifeValue 为负数,就抛出 NoLifeValueException,异常信息为“生命值不能为负数”
如果 lifeValue 不为负数,给成员 lifeValue 赋值
5)重写 toString 方法
3.定义测试类:
1)使用有参构造创建 Person 对象,生命值传入一个负数
2)使用空参构造创建 Person 对象
调用 setLifeValue(int lifeValue) 方法,传入一个正数,运行程序
调用 setLifeValue(int lifeValue) 方法,传入一个负数,运行程序
3)分别对1)和2)处理异常和不处理异常进行运行
public class Test2 {public static void main(String[] args) {
// try {
// Person p1 = new Person("张三", 5);
// System.out.println(p1);
// } catch (Exception e) {
// e.printStackTrace();
// }// try {
// Person p2 = new Person("张三", -5);
// System.out.println(p2);
// } catch (Exception e) {
// e.printStackTrace();
// }// try {
// Person p3 = new Person();
// p3.setName("张三");
// p3.setLifeValue(5);
// System.out.println(p3);
// } catch (Exception e) {
// e.printStackTrace();
// }try {Person p4 = new Person();p4.setName("张三");p4.setLifeValue(-5);System.out.println(p4);} catch (Exception e) {e.printStackTrace();}}
}class Person {private String name;private int lifeValue;public Person() {}public Person(String name, int lifeValue) {this.name = name;setLifeValue(lifeValue);}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getLifeValue() {return lifeValue;}public void setLifeValue(int lifeValue) {if(lifeValue < 0) {throw new NoLifeValueException("生命值不能为负数");}else {this.lifeValue = lifeValue;}}@Overridepublic String toString() {return "Person{" +"name='" + name + '\'' +", lifeValue=" + lifeValue +'}';}
}class NoLifeValueException extends RuntimeException {public NoLifeValueException() {}public NoLifeValueException(String message) {super(message);}
}
用户注册
1.自定义异常类 UsernameAlreadyExistsException(用户名已存在)继承 Exception
2.自定义异常类 LoginFailException(登录失败异常) 继承 Exception
3.用户类 User,包含私有化属性用户名和密码,提供有参和无参构造器,提供 get/set 方法
4.用户管理类 UserManager:
1)包含如下成员变量:
private static User[] arr; //存储已经注册的用户
private static int total; //存储实际注册的用户数量
2)包含无参构造器:
3)包含如下方法:
public void checkUsernameExists(String username) :检查用户名是否已经存在,如果已经存在,抛出 UsernameAlreadyExistsException(用户名已存在异常)
public void add(User user):添加新用户到 arr 数组中
public void login(User user):判断用户名和密码是否正确,如果没有匹配的用户名和密码,抛出 LoginFailException(登录失败异常)
5.测试类,实现如下运行效果
--------尚硅谷----------
1、注册
2、登录
3、退出
请选择:
1
用户名:chai
密码:123456
注册成功
--------尚硅谷----------
1、注册
2、登录
3、退出
请选择:
1
用户名:chai
用户名已存在
用户名:lin
密码:123456
注册成功
--------尚硅谷----------
1、注册
2、登录
3、退出
请选择:
2
用户名:chai
密码:123456
登录成功
--------尚硅谷----------
1、注册
2、登录
3、退出
请选择:
2
用户名:lin
密码:654321
LoginFailException: 登录失败
at UserManager.login(Test3.java:140)
at Test3.login(Test3.java:41)
at Test3.main(Test3.java:23)
--------尚硅谷----------
1、注册
2、登录
3、退出
请选择:
3
import java.util.Scanner;public class Test3 {private static Scanner sc = new Scanner(System.in);private static UserManager manager = new UserManager();public static void main(String[] args) {boolean flag = true;while (flag) {System.out.println("--------尚硅谷----------");System.out.println("\t\t1、注册");System.out.println("\t\t2、登录");System.out.println("\t\t3、退出");System.out.println("\t请选择:");int i = sc.nextInt();switch (i) {case 1:regist();break;case 2:login();break;case 3:flag = false;break;}}sc.close();}private static void login() {System.out.print("用户名:");String userName = sc.next();System.out.print("密码:");String password = sc.next();User user = new User(userName, password);try {manager.login(user);System.out.println("登录成功");} catch (LoginFailException e) {e.printStackTrace();}}private static void regist() {String userName;while (true) {System.out.print("用户名:");userName = sc.next();try {manager.checkUsernameExists(userName);break;} catch (UsernameAlreadyExistsException e) {System.err.println(e.getMessage());}}System.out.print("密码:");String password = sc.next();User user = new User(userName, password);manager.add(user);System.out.println("注册成功");}
}class User {private String username;private String password;public User() {}public User(String username, String password) {this.username = username;this.password = password;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}@Overridepublic String toString() {return "User{" +"username='" + username + '\'' +", password='" + password + '\'' +'}';}
}class UserManager {private static User[] arr; //存储已经注册的用户private static int total = 0; //存储实际注册的用户数量public UserManager() {arr = new User[5];}public void checkUsernameExists(String username) throws UsernameAlreadyExistsException {for (int i = 0; i < total; i++) {if(username.equals(arr[i].getUsername())) {throw new UsernameAlreadyExistsException("用户名已存在");}}}public void add(User user) {if(total >= arr.length) {User[] newArr = new User[arr.length * 2];for (int i = 0; i < total; i++) {newArr[i] = arr[i];}arr = newArr;}arr[total] = user;total++;}public void login(User user) throws LoginFailException {for (int i = 0; i < total; i++) {if(user.getUsername().equals(arr[i].getUsername()) && user.getPassword().equals(arr[i].getPassword())) {return;}}throw new LoginFailException("登录失败");}
}class UsernameAlreadyExistsException extends Exception {public UsernameAlreadyExistsException() {}public UsernameAlreadyExistsException(String message) {super(message);}
}class LoginFailException extends Exception {public LoginFailException() {}public LoginFailException(String message) {super(message);}
}