系列文章目录
作业1
代码
(1)自己写的
代码如下:(没有考虑代码的健壮性)
package studyhan.demo1;
public class Hello {
public static void main(String[] args) {
A01 t1 = new A01();
double number[] = {2.2,3.4,5.6};
System.out.println(t1.max(number));
}
}
class A01{
public double max(double... num){
double maxnumber = num[0];
for(int i = 1; i < num.length; i ++){
if(maxnumber < num[i]){
maxnumber = num[i];
}
}
return maxnumber;
}
}
结果如下:
(2)老师写的
代码如下:(考虑了代码的健壮性)
//编写一个main方法
public static void main(String[] args) {
A01 a01 = new A01();
double[] arr = {1, 1.4, -1.3, 89.8, 123.8 , 66}; //;{};
Double res = a01.max(arr);
if(res != null) {
System.out.println("arr的最大值=" + res);
} else {
System.out.println("arr的输入有误, 数组不能为null, 或者{}");
}
}
}
/*
编写类A01,定义方法max,实现求某个double数组的最大值,并返回
思路分析
1. 类名 A01
2. 方法名 max
3. 形参 (double[])
4. 返回值 double
先完成正常业务,然后再考虑代码健壮性
*/
class A01 {
public Double max(double[] arr) {
//老韩先判断arr是否为null,然后再判断 length 是否>0
if( arr!= null && arr.length > 0 ) {
//保证arr至少有一个元素
double max = arr[0];//假定第一个元素就是最大值
for(int i = 1; i < arr.length; i++) {
if(max < arr[i]) {
max = arr[i];
}
}
return max;//double
} else {
return null;
}
}
}
①第6、26行为double
时,当第5行代码为double[] arr = {};
时,数组为空的,第31行再将最大值赋给数组第一个元素就不对了,故需要在前面加上判断数组是否为空,保证arr至少有一个元素,即第28行的if( arr.length > 0 )
。
②当对上一条进行改进后,满足28行则返回最大值max
,否则返回一个double
数,因为该方法要求返回的类型是double
型,但返回什么double
数都不太合适,故将第6、26行的double
改为Double
,Double
是一个包装类,满足时返回double
值即max
,不满足时返回null
,因对象可以为null
(引用型数据可以为null
)。
③对上述改进后,还有一个问题:第5行代码也可为double[] arr = null;
因为数组是一个引用类型,其也可以为null
,此时第28行的if( arr.length > 0 )
相当于在执行if( null.length > 0 )
,此时内存中无地址,无法提取长度(即null没有分配空间,{}分配空间没有元素);故需要将第28行改为的if( arr!= null && arr.length > 0 )
。
④还有一个知识点:自动装箱自动拆箱的功能。
作业2
代码
(1) 自己写的(在老师基础上增加健壮性)
代码如下:
package studyhan.demo1;
public class Hello {
public static void main(String[] args) {
A02 t1 = new A02();
String b1[] = {"A","c","F"};
String a1 = "c";
int res = t1.find(a1,b1);
if(res != -1){
System.out.println(res);
}else {
System.out.println("该字符串不在字符串数组中");
}
}
}
class A02{
public int find(String a, String b[]) {
if (b != null && b.length > 0) {//传入的数组不为null且长度不为0
for (int i = 0; i < b.length; i++) {
if ((b[i]).equals(a)) {//数组b一定不会为空,避免a在前且为空时报错
return i;
}
}
}
return -1;
}
}
结果如下:
(2)老师写的
public class Homework02 {
//编写一个main方法
public static void main(String[] args) {
String[] strs = {"jack", "tom", "mary","milan"};
A02 a02 = new A02();
int index = a02.find("milan", strs);
System.out.println("查找的index=" + index);
}
}
//编写类A02,定义方法find,实现查找某字符串是否在字符串数组中,
//并返回索引,如果找不到,返回-1
//分析
//1. 类名 A02
//2. 方法名 find
//3. 返回值 int
//4. 形参 (String , String[])
//
//自己补充代码健壮性
class A02 {
public int find(String findStr, String[] strs) {
//直接遍历字符串数组,如果找到,则返回索引
for(int i = 0; i < strs.length; i++) {
if(findStr.equals(strs[i])) {
return i;
}
}
//遍历完后,如果没有,就返回-1
return -1;
}
}
作业3
代码
(1)自己写的(比较麻烦)
代码如下:
package studyhan.demo1;
import java.util.Scanner;
public class Hello {
public static void main(String[] args) {
Book t1 = new Book();
Scanner myscanner = new Scanner(System.in);
double price = -1;
while(true){
System.out.println("是否输入书籍价格?y/n");
String answer = myscanner.next();
if("y".equals(answer)){
System.out.println("请输入书籍价格:");
price = myscanner.nextDouble();
double res = t1.updatePrice(price);
if(res != -1){
System.out.println("书籍价格为:" + res);
}else {
System.out.println("该书的价格有误!");
}
}else {
break;
}
}
}
}
class Book{
public double updatePrice(double price) {
if(price >= 0) {
if (price > 150) {
price = 150;
return price;
} else if (price > 100 && price < 150) {
price = 100;
return price;
} else {
return price;
}
}else {
return -1;
}
}
}
结果如下:
(2)老师写的(用了构造器和this关键字,比自己写的简单)
代码如下:
public class Homework03 {
//编写一个main方法
public static void main(String[] args) {
//测试
Book book = new Book("笑傲江湖", 300);
book.info();
book.updatePrice();//更新价格
book.info();
}
}
/*
编写类Book, 定义方法updatePrice,实现更改某本书的价格,
具体:如果价格>150,则更改为150,如果价格>100,更改为100,否则不变
分析
1. 类名 Book
2. 属性 price, name
3. 方法名 updatePrice
4. 形参 ()
5. 返回值 void
6. 提供一个构造器
*/
class Book {
String name;
double price;
public Book(String name, double price) {
this.name = name;
this.price = price;
}
public void updatePrice() {
//如果方法中,没有 price 局部变量, this.price 等价 price
if(price > 150) {
price = 150;
} else if(price > 100 ) {//隐含条件 && price < 150,其写不写都行}
price = 100;
}
}
//显示书籍情况
public void info() {
System.out.println("书名=" + this.name + " 价格=" + this.price);
}
}
作业4
代码
(1)自己写的
代码如下:
package studyhan.demo1;
public class Hello {
public static void main(String[] args) {
int oldarr[] = {1,2,3,4,5,6};
for (int i = 0; i < oldarr.length; i++) {
System.out.print(oldarr[i] + "\t");
}
System.out.println();
A03 a03 = new A03();
for (int i = 0; i < a03.copyArr(oldarr).length; i++) {
System.out.print(a03.copyArr(oldarr)[i] + "\t");
}
}
}
class A03{
public int[] copyArr(int oldarr[]){
int newarr[] = new int[oldarr.length];
for (int i = 0; i < oldarr.length; i++) {
newarr[i] = oldarr[i];
}
return newarr;
}
}
结果如下;
(2)老师写的
代码如下:
public class Homework04 {
//编写一个main方法
public static void main(String[] args) {
int[] oldArr = {10, 30, 50};
A03 a03 = new A03();
int[] newArr = a03.copyArr(oldArr);
//遍历newArr,验证
System.out.println("==返回的newArr元素情况==");
for(int i = 0; i < newArr.length; i++) {
System.out.print(newArr[i] + "\t");
}
}
}
/*
编写类A03, 实现数组的复制功能copyArr,输入旧数组,返回一个新数组,元素和旧数组一样
*/
class A03 {
public int[] copyArr(int[] oldArr) {
//在堆中,创建一个长度为 oldArr.length 数组
int[] newArr = new int[oldArr.length];
//遍历 oldArr,将元素拷贝到 newArr
for(int i = 0; i < oldArr.length; i++) {
newArr[i] = oldArr[i];
}
return newArr;
}
}
作业5
代码
(1)自己写的
代码如下:
package studyhan.demo1;
public class Hello {
public static void main(String[] args) {
Circle circle = new Circle(3);
circle.perimeter();
circle.area();
}
}
class Circle{
double radius;
public Circle(double radius){
this.radius = radius;
}
public void area(){
double areac = Math.PI * Math.pow(radius,2);
System.out.println("圆的面积为:" + areac);
}
public void perimeter(){
double perimeterc = Math.PI * 2 * radius;
System.out.println("圆的面积为:" + perimeterc);
}
}
结果如下:
(2)老师写的
代码如下:
public class Homework05 {
//编写一个main方法
public static void main(String[] args) {
Circle circle = new Circle(3);
System.out.println("面积=" + circle.area());
System.out.println("周长=" + circle.len());
}
}
/*
定义一个圆类Circle, 定义属性:半径,提供显示圆周长功能的方法, 提供显示圆面积的方法
*/
class Circle {
double radius;
public Circle(double radius) {
this.radius = radius;
}
public double area() { //面积
return Math.PI * radius * radius;
}
public double len() { //周长
return 2 * Math.PI * radius;
}
}
作业6
代码
(1)自己写的(写的方法无返回值)
代码如下:
package studyhan.demo1;
public class Hello {
public static void main(String[] args) {
Cale cale = new Cale(2,4);
Cale cale1 = new Cale(2, 0);
System.out.println("第一个对象2和4");
cale.sum();
cale.difference();
cale.quotient();
cale.product();
System.out.println("第二个对象2和0");
cale1.sum();
cale1.difference();
cale1.quotient();
cale1.product();
}
}
class Cale {
double num1;
double num2;
public Cale(double num1, double num2) {
this.num1 = num1;
this.num2 = num2;
}
public void sum() {
double sumtotal;
sumtotal = num1 + num2;
System.out.println("两数之和为:" + sumtotal);
}
public void difference(){
double differencetotal;
differencetotal = num1 - num2;
System.out.println("两数之差为:" + differencetotal);
}
public void quotient() {
double quotienttotal;
if (num2 != 0) {
quotienttotal = num1 / num2;
System.out.println("两数之商为:" + quotienttotal);
}else {
System.out.println("分母为0,请重新输入!");
}
}
public void product(){
double producttotal;
producttotal = num1 * num2;
System.out.println("两数之积为:" + producttotal);
}
}
结果如下:
(2)老师写的(写的方法有返回值,在求商时需要包装类Double
)
代码如下:
public class Homework06 {
//编写一个main方法
public static void main(String[] args) {
Cale cale = new Cale(2, 10);
System.out.println("和=" + cale.sum());
System.out.println("差=" + cale.minus());
System.out.println("乘=" + cale.mul());
Double divRes = cale.div();
if(divRes != null) {
System.out.println("除=" + divRes);
}
}
}
/*
编程创建一个Cale计算类,在其中定义2个变量表示两个操作数,
定义四个方法实现求和、差、乘、商(要求除数为0的话,要提示) 并创建两个对象,分别测试
*/
class Cale {
double num1;
double num2;
public Cale(double num1, double num2) {
this.num1 = num1;
this.num2 = num2;
}
//和
public double sum() {
return num1 + num2;
}
//差
public double minus() {
return num1 - num2;
}
//乘积
public double mul() {
return num1 * num2;
}
//除法
//
public Double div() {
//判断
if(num2 == 0) {
System.out.println("num2 不能为0");
return null;
} else {
return num1 / num2;
}
}
}
作业7
代码
自己写的
代码如下:
package studyhan.demo1;
public class Hello {
public static void main(String[] args) {
Dog dog = new Dog("derder", "black", 2);
dog.show();
}
}
class Dog {
String name;
String color;
int age;
public Dog(String name, String color, int age) {
this.name = name;
this.color = color;
this.age = age;
}
public void show() {
System.out.println("该狗的姓名为:" + name);
System.out.println("该狗的颜色为:" + color);
System.out.println("该狗的年龄为:" + age);
}
结果如下:
作业8(代码阅读题)
代码
代码如下:
public class Test { //公有类
int count = 9; //属性
public void count1() { //Test类的成员方法
count=10;//这个count就是属性 改成 10
System.out.println("count1=" + count); //10
}
public void count2() { //Test类的成员方法
System.out.println("count=" + count++);
}
//这是Test类的main方法, 任何一个类,都可有main
public static void main(String args[]) {
//老韩解读
//1. new Test() 是匿名对象, 匿名对象使用后,就不能使用
//2. new Test().count1() 创建好匿名对象后, 就调用count1()
new Test().count1();
Test t1= new Test();
t1.count2();
t1.count2();
}
}
①第16行 new Test()
是一个匿名对象,因其创建了一个对象但没有将地址引用,在堆中,只能用一次,因没有任何变量指向它就会被销毁。
②count++先赋值再自增。
③第16-20行不能直接调用方法,即写成count1()或count2(),必须要先创建对象再调用方法,因:无法从静态上下文中引用非静态方法。(这里涉及到static关键字,main方法是静态方法,可以在没有创建类的实例对象的情况下直接调用,并且可以通过类名来访问。而非静态方法需要先创建类的实例对象,然后通过实例对象来调用,即静态方法调用非静态,需要new类再调)
输出结果:
作业9
代码
(1)自己写的
代码如下:
package studyhan.demo1;
public class Hello {
public static void main(String[] args){
Music excile = new Music("Excile", "12:34");
excile.play();
excile.getInfo();
}
}
class Music{
String name;
String times;
public Music(String name, String times) {
this.name = name;
this.times = times;
}
public void play(){
System.out.println("播放音乐");
}
public void getInfo(){
System.out.println("音乐名:" + name + "\n" + "音乐时长" + times);
}
}
结果如下:
(2)老师写的
代码如下:
public class Homework09 {
//编写一个main方法
public static void main(String[] args) {
Music music = new Music("笑傲江湖", 300);
music.play();
System.out.println(music.getInfo());
}
}
/*
义Music类,里面有音乐名name、音乐时长times属性,
并有播放play功能和返回本身属性信息的功能方法getInfo
*/
class Music {
String name;
int times;
public Music(String name, int times) {
this.name = name;
this.times = times;
}
//播放play功能
public void play() {
System.out.println("音乐 " + name + " 正在播放中.... 时长为" + times + "秒");
}
//返回本身属性信息的功能方法getInfo
public String getInfo() {
return "音乐 " + name + " 播放时间为" + times;
}
}
作业10(代码阅读题)
代码
代码如下:
public class Homework10 {
//编写一个main方法
public static void main(String[] args) {
}
}
class Demo{
int i=100;
public void m(){
int j=i++;
System.out.println("i="+i);
System.out.println("j="+j);
}
}
class Test{
public static void main(String[] args){//运行它
Demo d1=new Demo();
Demo d2 = d1;
d2.m();
System.out.println(d1.i);
System.out.println(d2.i);
}
}
结果如下:
作业11
答案
作业12
分析
复用意思是构造器可以调用另一个构造器来帮助完成初始化,故可以从初始化少构造器的先写。
代码
老师写的+自己修改
代码如下:
package studyhan.demo1;
public class Hello {
//编写一个main方法
public static void main(String[] args) {
Employee employee = new Employee("jack", "male", 25, "leader", 23000);
System.out.println(employee.name + "\t" + employee.gender + "\t"
+ employee.age + "\t" + employee.position + "\t" + employee.salary);
}
}
/*
创建一个Employee类,
属性有(名字,性别,年龄,职位,薪水), 提供3个构造方法,可以初始化
(1) (名字,性别,年龄,职位,薪水),
(2) (名字,性别,年龄)
(3) (职位,薪水), 要求充分复用构造器
*/
class Employee {
//名字,性别,年龄,职位,薪水
String name;
String gender;
int age;
String position;
double salary;
//因为要求可以复用构造器,因此老韩先写属性少的构造器
//职位,薪水
public Employee(String position, double salary) {
this.position = position;
this.salary = salary;
}
//名字,性别,年龄
public Employee(String name, String gender, int age) {
this.name = name;
this.gender = gender;
this.age = age;
}
//名字,性别,年龄,职位,薪水
public Employee(String name, String gender, int age, String position, double salary) {
this(name, gender, age);//使用到 前面的 构造器
this.position = position;
this.salary = salary;
}
}
①第36行,this
在调用构造器时有一个条件:在构造器中访问另一个构造器时,必须放在第一句。
结果如下:
作业13
代码
(1)自己写的(printAreas
方法中没有用到传入的Circle
对象,有些不符题意,且在第31行每次都创建新的对象,不划算)
代码如下:
package studyhan.demo1;
public class Hello {
//编写一个main方法
public static void main(String[] args) {
Circle circle = new Circle();
PassObject passObject = new PassObject();
System.out.println("Radius" + "\t" + "Area");
passObject.printAreas(circle,5);
}
}
class Circle{
double radius;
//无参构造器
public Circle() {
}
//有参构造器
public Circle(double radius) {
this.radius = radius;
}
public double findArea(){
return Math.PI * Math.pow(this.radius,2);
}
}
class PassObject{
public void printAreas(Circle c,int times){
if(times > 0){
for (int i = 1; i <= times; i++) {
Circle circle = new Circle(i);
System.out.println((double)i + "\t"+ "\t" + circle.findArea());
}
}
}
}
结果如下:
(2)老师写的
代码如下:
public class Homework13 {
//编写一个main方法
public static void main(String[] args) {
Circle c = new Circle();
PassObject po = new PassObject();
po.printAreas(c, 5);
}
}
/*
题目要求:
(1) 定义一个Circle类,包含一个double型的radius属性代表圆的半径,findArea()方法返回圆的面积。
(2) 定义一个类PassObject,在类中定义一个方法printAreas(),该方法的定义如下:
public void printAreas(Circle c, int times) //方法签名/声明
(3) 在printAreas方法中打印输出1到times之间的每个整数半径值,以及对应的面积。例如,times为5,则输出半径1,2,3,4,5,以及对应的圆面积。
(4) 在main方法中调用printAreas()方法,调用完毕后输出当前半径值。
*/
class Circle { //类
double radius;//半径
public double findArea() {//返回面积
return Math.PI * radius * radius;
}
//添加方法setRadius, 修改对象的半径值
public void setRadius(double radius) {
this.radius = radius;
}
}
class PassObject {
public void printAreas(Circle c, int times) {
System.out.println("radius\tarea");
for(int i = 1; i <= times; i++) {//输出1到times之间的每个整数半径值
c.setRadius(i) ; //修改c 对象的半径值
System.out.println((double)i + "\t" + c.findArea());
}
}
}
结果如下:
作业14
代码
(1)自己写的
用到下文中的Random
类生成随机数。
Java生成随机数的4种方式,以后就用它了!、Java 生成随机数的 5 种方式,你知道几种?
代码如下:
package studyhan.demo1;
import java.util.Random;
import java.util.Scanner;
public class Hello {
//编写一个main方法
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Tom tom = new Tom();
while (true){
System.out.println("是否继续猜拳游戏?y/n");
String wish = scanner.next();
if("y".equals(wish)){
System.out.println("猜拳,0-石头,1-剪刀,2-布;请从0,1,2三个数中选择输入!");
int answer = scanner.nextInt();
tom.compare(answer);
}else {
break;
}
}
}
}
class Tom {
// 生成 Random 对象
Random random = new Random();
int win = 0;
int lose = 0;
//添加与电脑比较的方法,传入Tom每次猜的拳
public void compare(int answer) {
int number = random.nextInt(3);
System.out.println(number);//输出电脑生成的随机数
if (answer == 0 && number == 1 || answer == 1 && number == 2 || answer == 2 && number == 0) {
win++;
System.out.println("Tom" + "获胜" + win);
} else if (answer == number) {
System.out.println("平手");
} else {
lose++;
System.out.println("Tom" + "输了" + lose);
}
}
}
结果如下:
(2)老师写的(用了一维数组来接收输赢情况 ,二维数组来接收局数,Tom出拳情况以及电脑出拳情况 )
代码如下:
import java.util.Random;
import java.util.Scanner;
/*
请编写一个猜拳的游戏
有个人 Tom,设计他的成员变量. 成员方法, 可以电脑猜拳. 电脑每次都会随机生成 0, 1, 2
0 表示 石头 1 表示剪刀 2 表示 布
并要可以显示 Tom的输赢次数(清单), 假定 玩三次.
*/
// 测试类,主类
public class MoraGame {
// 测试
public static void main(String[] args) {
// 创建一个玩家对象
Tom t = new Tom();
// 用来记录最后输赢的次数
int isWinCount = 0;
// 创建一个二维数组,用来接收局数,Tom出拳情况以及电脑出拳情况
int[][] arr1 = new int[3][3];
int j = 0;
// 创建一个一维数组,用来接收输赢情况
String[] arr2 = new String[3];
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < 3; i++) { //比赛3次
// 获取玩家出的拳
System.out.println("请输入你要出的拳(0-拳头,1-剪刀,2-布):");
int num = scanner.nextInt();
t.setTomGuessNum(num);
int tomGuess = t.getTomGuessNum();
arr1[i][j + 1] = tomGuess;
// 获取电脑出的拳
int comGuess = t.computerNum();
arr1[i][j + 2] = comGuess;
// 将玩家猜的拳与电脑做比较
String isWin = t.vsComputer();
arr2[i] = isWin;
arr1[i][j] = t.count;
// 对每一局的情况进行输出
System.out.println("=========================================");
System.out.println("局数\t玩家的出拳\t电脑的出拳\t输赢情况");
System.out.println(t.count + "\t" + tomGuess + "\t\t" + comGuess + "\t\t" + t.vsComputer());
System.out.println("=========================================");
System.out.println("\n\n");
isWinCount = t.winCount(isWin);
}
// 对游戏的最终结果进行输出
System.out.println("局数\t玩家的出拳\t电脑的出拳\t\t输赢情况");
for (int a = 0; a < arr1.length; a++) {
for (int b = 0; b < arr1[a].length; b++) {
System.out.print(arr1[a][b] + "\t\t\t");
}
System.out.print(arr2[a]);
System.out.println();
}
System.out.println("你赢了" + isWinCount + "次");
}
}
// Tom类
class Tom { // 核心代码
// 玩家出拳的类型
int tomGuessNum; //0,1,2
// 电脑出拳的类型
int comGuessNum; //0,1,2
// 玩家赢的次数
int winCountNum;
// 比赛的次数
int count = 1; //一共比赛3次
public void showInfo() {
//....
}
/**
* 电脑随机生成猜拳的数字的方法
* @return
*/
public int computerNum() {
Random r = new Random();
comGuessNum = r.nextInt(3); // 方法 返回 0-2的随机数
// System.out.println(comGuessNum);
return comGuessNum;
}
/**
* 设置玩家猜拳的数字的方法
* @param tomGuessNum
*/
public void setTomGuessNum(int tomGuessNum) {
if (tomGuessNum > 2 || tomGuessNum < 0) {
//抛出一个异常, 李同学会写,没有处理
throw new IllegalArgumentException("数字输入错误");
}
this.tomGuessNum = tomGuessNum;
}
public int getTomGuessNum() {
return tomGuessNum;
}
/**
* 比较猜拳的结果
* @return 玩家赢返回true,否则返回false
*/
public String vsComputer() {
//比较巧
if (tomGuessNum == 0 && comGuessNum == 1) {
return "你赢了";
} else if (tomGuessNum == 1 && comGuessNum == 2) {
return "你赢了";
} else if (tomGuessNum == 2 && comGuessNum == 0) {
return "你赢了";
} else if (tomGuessNum == comGuessNum){
return "平手";
} else {
return "你输了";
}
}
/**
* 记录玩家赢的次数
* @return
*/
public int winCount(String s) {
count++; //控制玩的次数
if (s.equals("你赢了")) { //统计赢的次数
winCountNum++;
}
return winCountNum;
}
}
结果如下: