《Java黑皮书基础篇第10版》 第11章【习题】

这篇具有很好参考价值的文章主要介绍了《Java黑皮书基础篇第10版》 第11章【习题】。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

Java语言程序设计 习题第十一章

11.2章节习题

11.1 下面说法是真是假? 一个子类是父类的子集

不是,子类可以拥有父类的数据域和方法,还可以拥有自己独有的数据域和方法

11.2 使用什么关键字来定义一个子类?

extends

11.3 什么是单一继承?什么是多重继承? Java支持多重继承吗?

单一继承是一个子类只能有一个父类

多重继承是一个子类可以有多个父类

Java不支持多重继承。在Java中,一个子类只能有一个父类,但是一个父类可以有多个子类

11.3章节习题

11.4 下面a中类C的运行结果输出什么? 编译b中的程序的时候将出现什么问題?

class A { 
  public A() {
		System.out.println("A's no-arg constructor is invoked");
	} 
}

class B extends A { 
	//B类虽然没有构造方法,但是编译器会自动创建一个无参构造方法
	//public B() {
	//同时,由于B没有明确的调用父类A的构造方法,super()也会被默认的构建出来,去调用A的无参构造方法
	//super();
	//}
}

public class Test {
	public static void main(String[] args) {
		//调用B类的无参构造方法来创建实例
		B b = new B(); 
  }
}

输出结果:

A's no-arg constructor is invoked
class A {
	public A(int x) { 
  }
}

class B extends A { 
	//编译器默认加了super(),想要去调用A类的无参构造方法,但是A类没有无参构造方法,所以报错
	public B() {
	}
}

public class C {
	public static void main(String[] args) {
		B b = new B(); 
  }
}

11.5 子类如何调用它的父类的构造方法?

使用关键字super

11.6 下面的说法是真是假: 当从子类调用构造方法时,它的父类的无参构造方法总是会被调用?

假,如果子类明确的调用了父类的有参构造方法,那么父类的无参构造方法就不会再被调用

11.4章节习题

11.7 下面说法是真是假:可以重写父类中定义的私有方法?

假,子类重写父类中的私有方法实际上是新定义了一个方法,和父类方法没有关系

11.8 下面说法是真是假:可以重写父类中定义的静态方法?

假,只能重写有访问权限的非private方法

11.9 如何从子类中显式的调用父类的构造方法?

使用super()

11.10 如何从子类中调用一个被重写的父类的方法?

使用super.method()

11.5章节习题

11.11 指出下面代码的错误:

public class Test {
	private double radius;

	//需要一个无参构造方法供B类中的构造方法来调用
	//public Test() {
	//}
	
	public Test(double radius) { 
		//需要使用关键字this来指向数据域,不然就是局部变量了
		radius = radius;
	}

	public double getRadius() { 
		return radius;
	}

	public double getArea() {
		return radius * radius * Math.PI;
		}
	}

class B extends Test {
	private double length;

	B(double radius, double length) {
		//父类的字段是private,不可以直接访问,需要使用super关键字来调用父类的构造方法来访问字段
		Test(radius); 
		//需要使用关键字this来指向数据域,不然就是局部变量了
		length = length;
	}

	@Override
	public double getArea() { 
		return getArea() * length;
	}
}

11.12 解释方法重载和方法重写的不同之处。

对于方法重写,首先必须保证方法签名和返回值都相同,只有方法体是不同的,其次需要保证必须是子类重写了父类的方法,在Java中提供了@Override来检测是否重写了父类。

对于方法重载,首先只要返回值(大多数情况)和方法名相同即可,方法参数和方法体都可以不同;其次可以重载同一个类或父类的方法。

11.13 如果子类中的方法具有和它父类中的方法完全相同的方法签名,且返回值类型也相同,那么这是方法重写还是方法重载呢?

Override

11.14 如果子类中的一个方法具有和它父类中的方法完全相同的方法签名,但返回值类型不相同,这会存在问题吗?

11.15 如果子类中的一个方法具有和它父类中的方法相同的名字,但参数类型不同,那么这是方法重写还是方法重载呢?

Overload

11.16 使用@Override标注的好处是什么?

在Java中提供了@Override来检测是否重写了父类。

11.8章节习题

11.17 什么是多态? 什么是动态绑定?

多态意味着子类可以安全地进行向上转型,即子类型的实例对象可以指向父类型的引用变量;

动态绑定意味着实例对象调用实例方法时,是基于运行时实际的实例对象类型来调用的,并不是基于引用变量的声明类型

11.18 描述方法匹配和方法绑定之间的不同。

方法匹配:只要方法名,参数类型、数量、顺序一致,就可以根据引用变量的类型去匹配方法

方法绑定:运行时期才能决定实例对象的类型并用这个类型的实例去匹配方法

11.19 可以将以下实例赋值给Object[]类型的变置吗,new int[50]、new Integer[50]、new String[50] 或者 new Object[50]?

New int[50]不行,其他都可以

11.20 下面代码中哪里有错误?

public class Test {
	public static void main(String[] args) {
		Integer[] list1 = {12, 24, 55, 1};
		Double[] list2 = {12.4, 24.0, 55.2, 1.0}; 
		int[] list3 = {1, 2, 3};
		printArray(list1);
		printArray(list2);
		//在调用printArray()方法时,传入了一个int数组,但是该方法只接受一个Object数组作为参数,因此会导致编译错误。在Java中,int是一个基本类型,不属于某一个类或包,不是一个对象,而Integer是一个对象。在Java中,基本类型和对象类型之间不能自动转换。
		printArray(list3);
  }

	public static void printArray(Object[] list) { 
    for (Object o: list)
			System.out.print(o + " ");
		System.out.println(); 
  }
}

11.21 给出下面代码的输出。

public class Test {
	public static void main(String[] args) {
			new Person().printPerson();
			new Student().printPerson(); 
	}
}

class Student extends Person { 
	@Override
	public String getInfo() {
		return "Student"; 
		}
}

class Person {
	public String getInfo() {
		return "Person"; 
		}

	public void printPerson() { 
		System.out.println(getInfo());
	} 
}

输出结果:

Person
Student
public class Test {
	public static void main(String[] args) {
		new Person().printPerson();
		new Student().printPerson(); 
	}
}

class Student extends Person {
  //private字段不可以访问,所以不可以Override
	private String getInfo() {
		return "Student"; 
	}
}

class Person {
	private String getInfo() {
		return "Person"; 
		}

	public void printPerson() { 
		System.out.println(getInfo());
	} 
}

输出结果:

Person
Person

11.22 给出下面程序的输出。

public class Test {
	public static void main(String[]args) {
		A a = new A(3); 
  }
}

class A extends B {
  public A(int t) {
		System.out.println("A's constructor is invoked");
  }
}

class B {
	public B() {
		System.out.println("B's constructor is invoked"); 
  }
}

输出结果:

B's constructor is invoked
A's constructor is invoked

11.23 给出下面程序的输出:

public class Test {
	public static void main(String[] args) {
		new A();
		new B();
  }
}

class A { 
	int i = 7;
	//对于new A(),首先会来匹配执行以下代码,并且A直接继承自Object,构造方法继承链终止。setI是方法重写,根据多态,会根据实例对象的实际类型匹配方法,所以会执行A类的setI方法
	//(2/2)构造方法继承链至此,执行setI,setI是方法重写,根据多态,会根据实例对象的实际类型匹配方法,所以会执行B类的setI方法
    public A() {
		setI(20);
		System.out.println("i from A is " + i);
}
  
	public void setI(int i) { 
    this.i = 2 * i;
	} 
}

class B extends A { 
	//(1/2)对于new B(),首先会来匹配执行以下代码,并且B直接继承自A,构造方法继承链向上继续
	public B() {
		System.out.println("i from B is " + i); 
  }

	public void setI(int i) { 
		this.i = 3 * i;
	} 
}

输出结果:

i from A is 40
i from A is 60
i from B is 60
11.9章节习题

11.24 下面的说法是对还是错?

• 总可以成功地将子类的实例转换为父类。

对,即为向上转型

• 总可以成功地将父类的实例转换为子类。

错,不一定成功,可以利用instanceof判断

11.25 对于程序清单11-1和程序清单11-2中的GeometricObject类和Circle类,回答下面的问题:

a. 假设circle和object如下创建:

Circle circle = new Circle(1);
GeometricObject object = new GeometricObject();

下面的布尔表达式的值是 true 还是 false ?

//true
(circle instanceof GeometricObject) 
//true
(object instanceof GeometricObject) 
//true
(circle instanceof Circle)
//false
(object instanceof Circle)

b. 下面的语句能够成功编译吗?

Circle circle = new Circle(5) ;
GeometricObject object = circle; 

可以,这是向上转型

c. 下面的语句能够成功编译吗?

GeometricObject object = new GeometricObject(); 
Circle circle = (Circle)object;

不可以

11.26 假设 Fruit、Apple、Orange、GoldenDelicious 和 Macintosh 如下面的继承层次定义:

《Java黑皮书基础篇第10版》 第11章【习题】

假设给出以下代码 :
Fruit fruit = new GoldenDelicious();

Orange orange = new Orange();

回答下面的问题:

a. fruit instanceof Fruit的值为 true 吗?

True

b. fruit instanceof Orange 的值为 true 吗?

False

c.fruit instanceof Apple的值为true吗?

True

d.fruit instanceof GoldenDelicious 的值为 true 吗?

True

e.fruit instanceof Macintosh的值为true吗?

False

f.orange instanceof Orange 的值为 true 吗?

True

g.orange instanceof Fruit 的值为 true 吗?

True

h.orange instanceof Apple 的值为 true 吗?

False

i.假设makeApple Cider方法定义在Apple类中。fruit可以调用这个方法吗?orange可以调用这个方法吗?

都不可以

j.假设makeOrangeJuice方法定义在Orange类中。orange可以调用这个方法吗?fruit可以调用这个方法吗?

orange可以,但是fruit不可以

k.语句 Orange p=new Apple() 是否合法?

不合法

必须要在同一个继承链,才可以进行类型转化

l.语句Macintosh p=new Apple()是否合法?

不合法

需要使用转型括号()来进行转化尝试

m.语句Apple p=new Macintosh()是否合法?

合法

11.27 下面代码中的错误是什么?

public class Test {
	public static void main(String[] args) {
		Object fruit = new Fruit();
    //Fruit实际上是父类,不能把父类变成子类
		Object apple = (Apple)fruit;
  }
}

class Apple extends Fruit {
}

class Fruit {
}
11.10章节习题

11.28 每个对象都有 toString 方法和 equals 方法吗?它们从何而来?如何使用?重写这些方法合适吗?

都有,从Object来,使用object1.equals(object2);,非常合适

11.29 当覆盖equals方法时,常见的错误就是在子类中输错它的签名。例如:equals 方法被错误地写成equals(Circle circle) , 如下面a中的代码所示;应该使用如b中所示的 equals(Object circle)替换它。分别给出运行a和b中的Test类和Circle类的输出。

public class Test {
  public static void main(String[] args) {
		Object circle1 = new Circle();
		Object circle2 = new Circle(); 		
    System.out.println(circle1.equals(circle2));
	} 
}

a:

class Circle { 
  double radius;

  public boolean equals(Circle circle) { 
    return this.radius == circle.radius;
	} 
}

输出结果false

b:

class Circle { 
  double radius;

  public boolean equals(Object circle) { 
    return this.radius == ((Circle)circle).radius; 
  }
}

输出结果true

如果 Test 类中的 Object 换成 Circle, 那么分别使用 a 和 b 中的 Circle 类来运行 Test 将输出什么?

都是true

11.11章节习题

11.30 如何实现以下功能?

a.创建一个存储双精度值的 ArrayList。

ArrayList<Double> decimals = new ArrayList<>();

b.向数组列表中追加一个对象。

decimals.add();

c.在数组列表的开始位置插人一个对象。

decimals.add(0, 3.14);

d.找出数组列表中所包含对象的个数。

decimals.size();

e. 从数组列表中刪除给定对象。

decimals.remove(3.14);

f. 从数组列表中删除最后一个对象。

decimals.remove(decimals.size() - 1);

g.检测一个给定的对象是否在数组列表中。

decimal.contains(3.14):

h.从数组列表中获取指定下标位置的对象。

decimal.get(1);

11.31 请找出下面代码中的错误:

ArrayList<String> list = new ArrayList<>(); list.add("Denver");
list.add("Austin");
//已经制定了ArrayList的类型是String,就不可以再上传Date
list.add(new java.util.Date());
String city = list.get(0); 
//超过范围了
list.set(3, "Dallas"); 
System.out.println(list.get(3));

11.32 假定ArrayList list包含{“Dallas”,“Dallas”,“Houston”,“Dallas”}。调用list.remove(“Dallas”)—次之后的列表是什么?下面语句可以从列表中删除所有具有值"Dallas"的元素么?如果不能,修改代码。

for (int i = 0; i < list.size(); i++)
	list.remove("Dallas");

如果只调用一次remove,列表会变成{“Dallas”,“Houston”,“Dallas”}

这个语句不可以删除所有Dallas,因为随着不同的Dallas被删除,ArrayList的length是在不断变小的,最后会导致循环提前终止

for (int i = 0; i < list.size(); i++) {
  if (list.remove(element))
    i--;
}

11.33 解释为什么下面代码显示[1,3],而不是[2,3]。

ArrayList<Integer> list = new ArrayList<>(); list.add(1);
list.add(2);
list.add(3);
list.remove(1); System.out.println(list);

remove(1)移除的不是数字1,而是在数组中index=1的元素

11.34 解释为什么下面代码是错误的。

ArrayList<Double> list = new ArrayList<>();
list.add(1);

1被当成了整数类型

11.12章节习题

11.35 改正下面语句中的错误:

int[] array = {3, 5, 95, 4, 15, 34, 3, 6, 5};
ArrayList<Integer> list = new ArrayList<>(Arrays.asList(array));

//基本数据类型不可以传递给ArrayList,ArrayList中的元素必须是对象
Integer[] array = {3, 5, 95, 4, 15, 34, 3, 6, 5};
	  ArrayList<Integer> list = new ArrayList<>(Arrays.asList(array));

11.36 改正下面语句中的错误:

int[] array = {3, 5, 95, 4, 15, 34, 3, 6, 5}; System.out.println(java.util.Collections.max(array));

//只有ArrayList才可以使用max方法,普通的Array不行
 Integer[] array = {3, 5, 95, 4, 15, 34, 3, 6, 5}; 
	  ArrayList<Integer> list = new ArrayList<>(Arrays.asList(array));
	  System.out.println(java.util.Collections.max(list));
11.14章节习题

11.37 应该在类上使用什么修饰符才能使同一个包中的类可以访问它,而不同包中的类不能访问它?

default修饰符,也就是没有修饰符

11.38 应该用什么修饰符才能使不同包中的类不能访问这个类,而任何包中的子类都可以访问它?

protected

11.39 在下面的代码中,类A和类B在同一个包中。如果a中的问号被空白代替,那么类B能编译吗?如果问号被private代替,那么类B能编译吗?如果问号被protected代替,类B能编译吗?

能、不能、能

11.40 在下面的代码中,类A和类B在不同的包中。如果a中的问号被空白代替,那么类B能编译吗?如果问号被private代替,那么类B能编译吗?如果问号被protected代替,那么类B 能编译吗?

不能、不能、能

11.15章节习题

11.41 如何防止一个类被扩展? 如何防止一个方法被重写?

使用final修饰符

11.42 指出下面语句是对还是错:

a.被保护的数据或方法可以被同一包中的任何类访问。

正确

b.被保护的数据或方法可以被不同包中的任何类访问。

错误

c.被保护的数据或方法可以被任意包中它的子类访问。

正确

d.最终类可以有实例。

正确

e.最终类可以被扩展。

错误

f.最终方法可以被重写。

错误

编程练习题

11.1(三角形类Triangle)

设计一个名为Triangle的类来扩展GeometricObject类。该类包括:

• 三个名为side1、side2和side3的double数据域表示这个三角形的三条边,它们的默认值是1.0。

• 一个无参构造方法创建默认的三角形。

• 一个能创建带指定 side1、side2 和 side3 的三角形的构造方法。

• 所有三个数据域的访问器方法。

• —个名为 getArea()的方法返回这个三角形的面积。

• 一个名为 getPerimeter() 的方法返回这个三角形的周长。

• 一个名为 toString()的方法返回这个三角形的字符串描述。

计算三角形面积的公式参见编程练习题2.19。toString()方法的实现如下所示:

return "Triangle: side1 = " + side1 + " side2 = " + side2 + " side3 = " + side3;

画出 Triangle 类和 GeometricObject 类的 UML 图,并实现这些类。编写一个测试程序, 提示用户输入三角形的三条边 、顔色以及一个 Boolean 值表明该三角形是否填充。程序应该使用输人创建一个具有这些边并设置color 和 filled 属性的三角形。程序应该显示面积、边长、 顔色以及表明是否填充的真或者假的值。

Test.java

import java.util.Scanner;

public class Test {
	public static void main(String[] args) {
	 Scanner scanner = new Scanner(System.in);
	 System.out.print("Input 3 sides in a triangle: ");
	 double side1 = scanner.nextDouble();
	 double side2 = scanner.nextDouble();
	 double side3 = scanner.nextDouble();
	 System.out.print("Input color: ");
	 scanner.nextLine();
	 String color = scanner.nextLine();
	 System.out.print("Input filling situations (true for filled and false for unfilled): ");
	 boolean filled = scanner.nextBoolean();
	 
	 Triangle test1 = new Triangle(side1, side2, side3, color, filled);
	 System.out.println(test1.toString());
	 System.out.println("Area is " + test1.getArea());
	}
}

Triangle.java

		/*_________________________________________________________________
		|					     GeometricObject						   |  
		|__________________________________________________________________|
										^
										|
		 __________________________UML DIAGRAM______________________________
		/*																	|																															
		* 							  Triangle 								|
		*-------------------------------------------------------------------|
		* 	-side1 : double													|
		* 																	|	
		*   -side2 : double													|
		* 																	|
		* 	-side3 : double													|								
		*-------------------------------------------------------------------|
		* 	+Triangle2D()													|
		* 	 																|
		* 	+Triangle2D(side1: double, side2: double, side3: double)		|
		* 																	|
		* 	+getSide1 : double												|
		* 																	|
		*   +getSide2 : double												|
		*    																|
		*   +getSide3 : double												|
		* 																	|
		* 	+getArea() : double												|
		* 																	|
		* 	+getPerimeter() : double										|
		* 																	|
		* 	+toString(): String 											|
		*___________________________________________________________________|  */


public class Triangle extends GeometricObject {
	private double side1;
	private double side2;
	private double side3;
	
	public Triangle() {
		side1 = 1.0;
		side2 = 1.0;
		side3 = 1.0;
	}
	
	public Triangle(double side1, double side2, double side3, String color, boolean filled) {
		this.side1 = side1;
		this.side2 = side2;
		this.side3 = side3;
		this.color = color;
		this.filled = filled;
	}
	
	public double getSide1() {
		return side1;
	}
	
	public double getSide2() {
		return side2;
	}
	
	public double getSide3() {
		return side3;
	}
	
	public double getArea() {
		double p = (side1 + side2 + side3) / 2.0;
	    return Math.sqrt(p * (p - side1) * (p - side2) * (p - side3));
	}
	
	public double getPerimeter() {
		return side1 + side2 + side3;
	}
	
    //这里复写了父类的toString()方法,可以同时得到两个toString()的返回值
	@Override
	public String toString() {
		return "Triangle: side1 = " + side1 + " side2 = " + side2 + " side3 = " + side3 + super.toString();
	}
}

GeometricObject.java

public class GeometricObject {
	protected String color; 
	protected boolean filled;
	private java.util.Date dateCreated;

	//Construct a default geometric object 
	public GeometricObject() { 
		dateCreated = new java.util.Date();
	}
 

	//Construct a geometric object with the specified color and filled value
	public GeometricObject(String color, boolean filled) { 
		dateCreated = new java.util.Date(); 
		this.color = color; 
		this.filled = filled;
	}

	public String getColor() {
		return color;
	}

	//Set a new color
	public void setColor(String color) { 
		this.color = color;
	}

	//Return filled. Since filled is boolean, its getter method is named isFilled
	public boolean isFilled() { 
		return filled;
	}

	//Set a new filled
	public void setFilled(boolean filled) { 
		this.filled = filled;
	}

	//Get dateCreated
	public java.util.Date getDateCreated() { 
		return dateCreated;
	}

	//Return a string representation of this object
	public String toString(){
		return "\ncreated on " + dateCreated + "\ncolor: " + color + " and filled: " + filled;
	}
}

输出结果:

Input 3 sides in a triangle: 3 4 5
Input color: blue
Input filling situations (true for filled and false for unfilled): true
Triangle: side1 = 3.0 side2 = 4.0 side3 = 5.0
created on Tue Apr 25 13:10:51 BST 2023
color: blue and filled: true
Area is 6.0
11.2 (Person、Student、Employee、Faculty 和 Staff 类)

设计一个名为 Person 的类和它的两个名为 Student 和 Employee 的子类。Employee 类又有子类:教员类 Faculty 和职员类 Staff。 每个人都有姓名、地址、电话号码和电子邮件地址。学生有班级状态(大一、大二、大三或大 四)。将这些状态定义为常量。一个雇员涉及办公室、工资和受聘日期。使用编程练习题 10.14 中定义的 MyDate 类为受聘日期创建一个对象。教员有办公时间和级别。职员有职务称号。覆盖每个类中的 toString 方法,显示相应的类别名字和人名。

画出这些类的UML图并实现这些类。编写一个测试程序,创建 Person、Student、 Employee、Faculty 和 Staff,并且调用它们的 toStringO 方法。

Test.java

public class Test {
	public static void main(String[] args) {
		Person person = new Person("Max", "Temple House", "1234-5678", "max@glook");
		Student student = new Student("Jean", "Spring House", "2344-4652", "jean@glook", 4);
		Employee employee = new Employee("Taylor", "First House", "3252-3252", "Taylorx@glook", "Main Office", 43000, new MyDate());
		Faculty faculty = new Faculty("Abin", "Sherren House", "9999-0000", "abin@glook", "8:00 - 16:00", "No.1");
		Staff staff = new Staff("Claudia", "Tower Bridge", "3452-7777", "claudia@glook", "General Manager");
		System.out.println(person.toString());
		System.out.println(student.toString());
		System.out.println(employee.toString());
		System.out.println(faculty.toString());
		System.out.println(staff.toString());
	}
}

Person.java

//________________________________________UML DIAGRAM_______________________________________________*
/*																									|
 * 							                 Person  												|
 *--------------------------------------------------------------------------------------------------|																 										|
 *  #name: String																					|
 *  																								|
 *  #address: String																				|
 *  																								|
 *  #tele: String																					|
 *  																								|
 *  #email: String																					|
 *--------------------------------------------------------------------------------------------------|
 * 	+Person()																						|
 * 																									|
 *  +Perosn(): (name: double, address: double, tele: double, email: double) 						|
 * 	 																								|
 * 	+toString(): String																				|
 *__________________________________________________________________________________________________|  */
 
public class Person {
	protected String name;
	protected String address;
	protected String tele;
	protected String email;
	
	public Person() {
		
	}
	
	public Person(String name, String address, String tele, String email) {
		this.name = name;
		this.address = address;
		this.tele = tele;
		this.email = email;
	}
	
	public String toString() {
		return "Person: " + name + " " + address + " " + tele + " " + email;
	}
}

Student.java

		/*_________________________________________________________________
		|					         Person						  		   |  
		|__________________________________________________________________|
										^
										|
		 __________________________UML DIAGRAM______________________________
		/*																	|																															
		* 							 Student								|
		*-------------------------------------------------------------------|
		* 	#FRESHMAN: int: (1)												|
		* 																	|
		*   #SOPHOMORE: int: (2)											|
		* 																	|
		*   #JUNIOR: int: (3)												|
		* 																	|
		*   #SENIOR: int: (4)												|
		*   																|
		*   #category: int													|								
		*-------------------------------------------------------------------|
		* 	+Student(): (name: double, address: double, tele: double, email: double, category: int) 
		* 																	|
		* 	+toString(): String 											|
		*___________________________________________________________________|  */

public class Student extends Person { 
	protected static final int FRESHMAN = 1;
	protected static final int SOPHOMORE = 2;
	protected static final int JUNIOR = 3;
	protected static final int SENIOR = 4;
	protected int category;
	
	public Student(String name, String address, String tele, String email, int category) {
		this.name = name;
		this.address = address;
		this.tele = tele;
		this.email = email;
		this.category = category;
	}
	
	@Override
	public String toString() {
		return "Student: " + name + " " + address + " " + tele + " " + email + " year: " + category;
	}
}

Employee.java

		/*_________________________________________________________________
		|					         Person						  		   |  
		|__________________________________________________________________|
										^
										|
		 __________________________UML DIAGRAM______________________________
		/*																	|																															
		* 							 Employee								|
		*-------------------------------------------------------------------|
		* 	#office: String													|
		* 																	|
		*   #salary: double													|
		* 																	|
		*   #date: MyDate													|						
		*-------------------------------------------------------------------|
		* 	+Employee()														|
		* 																	|
		*   +Employee(): (name: double, address: double, tele: double, email: double, office: String, salary: String, date: MyDate)
		* 																	|
		* 	+toString(): String 											|
		*___________________________________________________________________|  */

public class Employee extends Person { 
	protected String office;
	protected double salary;
	protected MyDate date;
	
	public Employee() {
		
	}
	
	public Employee(String name, String address, String tele, String email, String office, double salary, MyDate date) {
		this.name = name;
		this.address = address;
		this.tele = tele;
		this.email = email;
		this.office = office;
		this.salary = salary;
		this.date = date;
	}
	
	@Override
	public String toString() {
		return "Employee: " + name + " " + address + " " + tele + " " + email + " " + office + " " + salary + " created on: " + date;
	}
}

Faculty.java

		/*_________________________________________________________________
		|					         Employee						  	   |  
		|__________________________________________________________________|
										^
										|
		 __________________________UML DIAGRAM______________________________
		/*																	|																															
		* 							 Faculty								|
		*-------------------------------------------------------------------|
		* 	#officeHour: String													|
		* 																	|
		*   #rank: String													|	
		*-------------------------------------------------------------------|
		* 	+Faculty(): (name: double, address: double, tele: double, email: double, officeHour: String, rank: String)
		* 																	|
		* 	+toString(): String 											|
		*___________________________________________________________________|  */

public class Faculty extends Employee { 
	protected String officeHour;
	protected String rank;
	
	public Faculty(String name, String address, String tele, String email, String officeHour, String rank) {
		this.name = name;
		this.address = address;
		this.tele = tele;
		this.email = email;
		this.officeHour = officeHour;
		this.rank = rank;
	}
	
	@Override
	public String toString() {
		return "Faculty: " + name + " " + address + " " + tele + " " + email + " " + officeHour + " " + rank;
	}
}

Staff.java

		/*_________________________________________________________________
		|					         Employee						  	   |  
		|__________________________________________________________________|
										^
										|
		 __________________________UML DIAGRAM______________________________
		/*																	|																															
		* 							 Staff									|
		*-------------------------------------------------------------------|
		* 	#position: String												|					
		*-------------------------------------------------------------------|
		* 	+Staff(): (name: double, address: double, tele: double, email: double, position: String)
		* 																	|
		* 	+toString(): String 											|
		*___________________________________________________________________|  */

public class Staff extends Employee { 
	protected String position;
	
	public Staff(String name, String address, String tele, String email, String position) {
		this.name = name;
		this.address = address;
		this.tele = tele;
		this.email = email;
		this.position = position;
	}
	
	@Override
	public String toString() {
		return "Staff: " + name + " " + address + " " + tele + " " + email + " " + position;
	}
}

MyDate.java

import java.util.GregorianCalendar;

public class MyDate {
    GregorianCalendar gregorianCalendar = new GregorianCalendar();
    private int year;
    private int month;
    private int day;

    public MyDate() {
        this(System.currentTimeMillis());
    }

    public MyDate(long elapsedTime) {
        setDate(elapsedTime);
    }

    public MyDate(int year, int month, int day) {
        this.year = year;
        this.month = month;
        this.day = day;
    }


    public void setDate(long elapsedTime) {
        gregorianCalendar.setTimeInMillis(elapsedTime);
        this.year = gregorianCalendar.get(GregorianCalendar.YEAR);
        this.month = gregorianCalendar.get(GregorianCalendar.MONTH);
        this.day = gregorianCalendar.get(GregorianCalendar.DAY_OF_MONTH);
    }

    public int getYear() {
        return year;
    }

    public int getMonth() {
        return month;
    }

    public int getDay() {
        return day;
    }
}

输出结果:

Person: Max Temple House 1234-5678 max@glook
Student: Jean Spring House 2344-4652 jean@glook year: 4
Employee: Taylor First House 3252-3252 Taylorx@glook Main Office 43000.0 created on: MyDate@5305068a
Faculty: Abin Sherren House 9999-0000 abin@glook 8:00 - 16:00 No.1
Staff: Claudia Tower Bridge 3452-7777 claudia@glook General Manager
11.3 (账户类 Account 的子类)

在编程练习題9.7中定义了一个 Account 类来建模一个银行账户。一个账户有账号 、余额 、年利率、开户日期等属性,以及存款和取款等方法。创建两个检测支票账户(checking account)和储蓄账户(saving account)的子类。支票联户有一个透支限定额,但储蓄账户不能透支。

画出这些类的UML图并实现这些类。编写一个测试程序,创建 Account、 SavingsAccount 和 CheckingAccount 的对象,然后调用它们的 toString() 方法。

Test.java

public class Test {
	public static void main(String[] args) {
		CheckingAccount checking1 = new CheckingAccount();
		SavingAccount saving1 = new SavingAccount();
		checking1.deposit(5000);
		saving1.deposit(1000);
		System.out.println(checking1.toString());
		System.out.println(saving1.toString());
		checking1.withDraw(2000);
		saving1.withDraw(2000);
	}
}

Account.java

import java.util.Date;

class Account {
	protected int id;
	protected double balance;
	protected double annualInterestRate;
	protected Date dateCreated;
	
	Account() {
		id = 0;
		balance = 0;
		annualInterestRate = 0;
		dateCreated = new Date();
	}
	
	Account(int id, double balance) {
		this.id = id;
		this.balance = balance;
		annualInterestRate = 0;
		dateCreated = new Date();
	}
	
	int getId() {
		return id;
	}
	
	void setId(int newId) {
		this.id = newId;
	}
	
	double getBalance() {
		return balance;
	}
	
	void setbalance(int newBalance) {
		this.balance = newBalance;
	}
	
	double getAnnualInterestRate() {
		return annualInterestRate;
	}
	
	void setAnnualInterestRate(double newRate) {
		this.annualInterestRate = newRate;
	}
	
	Date getDateCreated() {
		return dateCreated;
	}
	
	double getMonthlyInterestRate() {
		return annualInterestRate / 1200;
	}
	
	double getMonthlyInterest() {
		return getMonthlyInterestRate() * balance;
	}
	
	void withDraw(double withdraw) {
		balance -= withdraw;
	}
	
	void deposit(double deposit) {
		balance += deposit;
	}
	
	@Override
    public String toString() {
        return "Account ID: " + getId() + "\nBalance: " + getBalance() +
                "\nDate created " + getDateCreated() + "\nCurrent Annual Rate: " + getAnnualInterestRate() + "\n";
    }
  }

CheckingAccount.java

import java.util.Date;

public class CheckingAccount extends Account {
	
	CheckingAccount() {
		id = 0;
		balance = 0;
		annualInterestRate = 0;
		dateCreated = new Date();
	}
	
	void withDraw(double withdraw) {
		if (balance - withdraw < -1000) {
			System.out.println("Do not have enough money");
		}
		balance -= withdraw;
	}
	
	@Override
    public String toString() {
        return "Checking Account ID: " + getId() + "\nBalance: " + getBalance() +
                "\nDate created " + getDateCreated() + "\nCurrent Annual Rate: " + getAnnualInterestRate() + "\n";
    }
}

SavingAccount.java

import java.util.Date;

public class SavingAccount extends Account {

	SavingAccount() {
			id = 0;
			balance = 0;
			annualInterestRate = 0;
			dateCreated = new Date();
		}
		
	void withDraw(double withdraw) {
			if (balance - withdraw < 0) {
				System.out.println("Do not have enough money");
			}
			balance -= withdraw;
		}
		
	@Override
	public String toString() {
	        return "Saving Account ID: " + getId() + "\nBalance: " + getBalance() +
	                "\nDate created " + getDateCreated() + "\nCurrent Annual Rate: " + getAnnualInterestRate() + "\n";
	    }
	}

输出结果:

Checking Account ID: 0
Balance: 5000.0
Date created Tue Apr 25 17:39:46 BST 2023
Current Annual Rate: 0.0

Saving Account ID: 0
Balance: 1000.0
Date created Tue Apr 25 17:39:46 BST 2023
Current Annual Rate: 0.0

Do not have enough money
11.4 ( ArrayList 的最大元素)

编写以下方法,返回一个整数 ArrayList 的最大值。如果列表为 null 或者列表的大小为0, 则返回 null 值。

public static Integer max(ArrayList<Integer> list)

编写一个测试程序,提示用户输人一个以0结尾的数值序列,调用该方法返回输人的最大数值。

Test.java

import java.util.ArrayList;
import java.util.Collections;

public class Test {
	public static void main(String[] args) {
		ArrayList<Integer> arrayList = new ArrayList<>();
		arrayList.add(1);
		arrayList.add(7);
		arrayList.add(9);
		arrayList.add(6);
		arrayList.add(12);
		arrayList.add(3);
		arrayList.add(11);
		System.out.print(Collections.max(arrayList));
	}
}

输出结果:

12
11.5 (课程类 Course)

重写程序淸单10-6中的 Course 类,使用 ArrayList 代替数组来存储学生。 为该类绘制新的 UML 图。不应该改变 Course 类的原始合约(即,构造方法和方法的定义都不应该改变,但私有的成员可以改变)。

Test.java

public class Test {
	public static void main(String[] args) {
		Course math = new Course("Math");
		math.addStudent("Ken");
		math.addStudent("Kevin");
		math.addStudent("Sean");
		math.addStudent("Henry");
		math.dropStudent(0);
		System.out.println(math.getCourseName());
		System.out.println(math.getNumberofStudents());
		System.out.println(math.getStudents());
	}
}

Course.java

import java.util.ArrayList;

//_________________________UML DIAGRAM______________________________*
/*																	|
* 							  Course  								|
*-------------------------------------------------------------------|
* 				                                                    |
*  -courseName: String	                 							|
*  -students: ArrayList<String>               						|
* 	                                                        		|
*-------------------------------------------------------------------|
*  ··········														|
*___________________________________________________________________|  */

public class Course {
	private String courseName;
	private ArrayList<String> students = new ArrayList<>(); 

	public Course(String courseName) { 
		this.courseName = courseName;
	}

	public void addStudent(String student) { 
		students.add(student);
	}
	
	public void dropStudent(int index){
		students.remove(index);
	}

	public String getStudents() { 
		return students.toString();
	}

	public int getNumberofStudents() { 
		return students.size();
	}

	public String getCourseName() {   
		return courseName;
	}
}

输出结果:

Math
3
[Kevin, Sean, Henry]
11.6 (使用 ArrayList)

编写程序,创建一个 ArrayList, 然后向这个列表中添加一个 Loan 对象、—个Date对象、一个字符串和一个Circle对象,然后使用循环调用对象的toString()方法,来显示列表中所有的元素。

Test.java

import java.util.ArrayList;
import java.util.Date;
//剩下的两个类之前编写过,现在找不到了-_-!
public class Test {
	public static void main(String[] args) {
		ArrayList<Object> object = new ArrayList<>();
		object.add(new Date());
		object.add("object");
		System.out.print(object.toString());
	}
}

输出结果:

[Wed Apr 26 15:35:22 BST 2023, object]
11.7 (打乱 ArrayList)

编写以下方法,打乱一个整数ArrayList中的元素。

import java.util.ArrayList;
import java.util.Collections;

public class Test {
	public static void main(String[] args) {
		ArrayList<Integer> list = new ArrayList<>();
		for (int i = 1; i <= 10; i++)
			list.add(i);
		System.out.println("Original list: " + list.toString());
		Collections.shuffle(list);
		System.out.println("Shuffled list: " + list.toString());
	}
}

输出结果:

Original list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Shuffled list: [3, 6, 7, 10, 9, 5, 8, 1, 4, 2]
**11.8 (新的Account类)

编程练习题9.7中给出了一个Account类,如下设计一个新的Account类:

• 添加一个 String 类型的新数据域 name 来存储客户的名字。

• 添加一个新的构造方法,该方法创建一个具有指定名字 、id 和收支额的账户。

• 添加一个名为transactions的ArrayList类型的新数据域.用于为账户存储交易。每笔交易都是一个 Transaction 类的实例。Transaction 类的定义如 11-6 所示。

• 修改 withdraw 和 deposit 方法,向 transactions 数组线性表添加一笔交易。

• 其他所有属性和方法都和编程练习題 9.7 中的一样。

编写一个测试程序,创建一个年利率为1.5%、收支额为1000、id为1122而名字为George的Account。向该账户存入30美元、40美元和50美元并从该账户中取出5美元、4美元和2美元。打印账户清单,显示账户持有者名字 、利率 、收支额和所有的交易。

《Java黑皮书基础篇第10版》 第11章【习题】

Test.java

public class Test {
	public static void main(String[] args) {
		Account account1 = new Account("Kevin", 27936);
		account1.deposit(5000);
		account1.withDraw(2000);
		System.out.println(account1.toString());
	}
}

Account.java

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;

class Account {
	protected String name;
	protected int id;
	protected double balance;
	protected double annualInterestRate;
	protected Date dateCreated;
	protected ArrayList<Transaction> transaction;
	
	Account() {
	}
	
	Account(String name, int id) {
		this.name = name;
		this.id = id;
		balance = 0;
		annualInterestRate = 3;
		dateCreated = new Date();
		transaction = new ArrayList<>();
	}
	
	int getId() {
		return id;
	}
	
	String getName() {
		return name;
	}
	
	void setId(int newId) {
		this.id = newId;
	}
	
	double getBalance() {
		return balance;
	}
	
	void setbalance(int newBalance) {
		this.balance = newBalance;
	}
	
	double getAnnualInterestRate() {
		return annualInterestRate;
	}
	
	void setAnnualInterestRate(double newRate) {
		this.annualInterestRate = newRate;
	}
	
	Date getDateCreated() {
		return dateCreated;
	}
	
	double getMonthlyInterestRate() {
		return annualInterestRate / 1200;
	}
	
	double getMonthlyInterest() {
		return getMonthlyInterestRate() * balance;
	}
	
	void withDraw(double withdraw) {
		balance -= withdraw;
		Transaction one = new Transaction(new Date(), "WUS", withdraw, "Withdraw");
		transaction.add(one);
	}
	
	void deposit(double deposit) {
		balance += deposit;
		Transaction one = new Transaction(new Date(), "DUS", deposit, "Deposit");
		transaction.add(one);
	}
	
	@Override
    public String toString() {
        return "User Name: " + getName() + "\nAccount ID: " + getId() + "\nBalance: " + getBalance() +
                "\nDate created " + getDateCreated() + "\nCurrent Annual Rate: " + getAnnualInterestRate() + "\n" + Arrays.toString(transaction.toArray());
    }
  }

Transaction.java

import java.util.Date;

public class Transaction{
	protected Date transDate;
	protected String type;
	protected double amount;
	protected String description;
	
	public Transaction(Date transDate, String type, double amount, String description) {
		this.transDate = new Date();
		this.type = type;
		this.amount = amount;
		this.description = description;
	}
	
	 @Override
	    public String toString() {
	        return "\nTransaction:\n" +
	                "Description: " + description +
	                ", Amount: $" + amount +
	                ", Type: " + type +
	                ", TransactionDate: " + transDate + "\n";
	    }
}

输出结果:

User Name: Kevin
Account ID: 27936
Balance: 3000.0
Date created Wed Apr 26 17:15:49 BST 2023
Current Annual Rate: 3.0
[
Transaction:
Description: Deposit, Amount: $5000.0, Type: DUS, TransactionDate: Wed Apr 26 17:15:49 BST 2023
, 
Transaction:
Description: Withdraw, Amount: $2000.0, Type: WUS, TransactionDate: Wed Apr 26 17:15:49 BST 2023
]
*11.9 (最大的行和列)

编写程序,随机将0和1填入一个n*n的矩阵,打印该矩阵,并且找出具有最多1的行和列。

import java.util.Scanner;

public class Test {
	public static void main(String[] args) {
		//提示用户输入一个整数n,并读取
		Scanner scanner = new Scanner(System.in);
		System.out.print("Enter the array size n: ");
		int n = scanner.nextInt();
		
		//创建整数n组成的n*n的老二维数组,随后创建两个新的,有2列的新二维数组,分别记载行和列各自1的数量
		int[][] arr = new int[n][n];
		int[][] indexRow = new int[n][2];
		int[][] indexColumn = new int[n][2];
		int row = 0;
		int column = 0;

		//遍历老二维数组并随机赋值0或1,同时,赋值当中每有一个1,就进行row+1,最后算出老数组当中1在每一行出现的次数
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				
				arr[i][j] = (int)(Math.random() * 2);
				if (arr[i][j] == 1)
					row++;
			}
			//新二维数组的第一列是从0开始的行号,第二列是老数组当中1在每一行出现的次数
			indexRow[i][0] = i;
			indexRow[i][1] = row;
			//需要让k归零,不然k会累加
			row = 0;
		}
		
		//老二维数组的列中当中每有一个1,就进行column+1,最后算出老数组当中1在每一列出现的次数
		for (int j = 0; j < n; j++) {
			for (int i = 0; i < n; i++) {
				if (arr[i][j] == 1)
					column++;
			}
			//新二维数组的第一列是从0开始的行号,第二列是老数组当中1在每一列出现的次数
			indexColumn[j][0] = j;
			indexColumn[j][1] = column;
			//需要让k归零,不然k会累加
			column = 0;
		}
		
		//打印老二维数组
		System.out.println("The random array is");
		for (int i = 0; i < arr.length; i++) {
		    for (int j = 0; j < arr[i].length; j++) {
		        System.out.print(arr[i][j] + " ");
		    }
		    System.out.println();
		}
		
		//在新二维数组中,需要给第二列求最大值,并返回最大值所在的行号,如果有两个相等的最大值,则需要同时返回他们对应的行号
		//这里先遍历一遍第二列,记录下最大值。然后再遍历一遍第二列,将和最大值相等的元素都打印出来。做两次,就可以求出行和列中最多1出现的对应行号和列号
		int maxRow = 0;
		int maxColumn = 0;
		for (int[] scan : indexRow) {
		    int val = scan[1];
		    if (val > maxRow) {
		        maxRow = val;
		    }
		}
		
		for (int[] scan : indexColumn) {
		    int val = scan[1];
		    if (val > maxColumn) {
		        maxColumn = val;
		    }
		}
		
		System.out.print("The largest row index: ");
		for (int i = 0; i < indexRow.length; i++) {
		    if (indexRow[i][1] == maxRow) {
		        System.out.print(i + " ");
		    }
		}
		
		System.out.println();
		System.out.print("The largest column index: ");
		for (int i = 0; i < indexColumn.length; i++) {
		    if (indexColumn[i][1] == maxColumn) {
		        System.out.print(i + " ");
		    }
		}
		
		//打印新二维数组,可以作为验证的参考,供今后使用
		System.out.println("\n");
		for (int i = 0; i < indexRow.length; i++) {
		    for (int j = 0; j < indexRow[i].length; j++) {
		        System.out.print(indexRow[i][j] + " ");
		    }
		    System.out.println();
		}
		
		System.out.println("\n");
		for (int i = 0; i < indexColumn.length; i++) {
		    for (int j = 0; j < indexColumn[i].length; j++) {
		        System.out.print(indexColumn[i][j] + " ");
		    }
		    System.out.println();
		}
		
		scanner.close();
	}
}

输出结果:

Enter the array size n: 5
The random array is
1 1 0 1 0 
1 0 0 1 1 
1 1 0 0 1 
1 1 1 0 0 
1 0 0 0 1 
The largest row index: 0 1 2 3 
The largest column index: 0 

0 3 
1 3 
2 3 
3 3 
4 2 


0 5 
1 3 
2 1 
3 2 
4 3 
11.10 (利用继承实现MyStack)

在程序清单11-10中,MyStack是用组合实现的。扩展ArrayList创建一个新的栈类。
画出这些类的 UML 图并实现 MyStack 类。编写一个测试程序,提示用户输人五个字符串,然后以逆序显示这些字符串。

public class Test {
	public static void main(String[] args) {
		MyStack test = new MyStack();
		test.push("Kevin");
		test.push("Sean");
		test.push("Ken");
		test.push("Henry");
		System.out.println(test.toString());
	}
}
import java.util.ArrayList;

public class MyStack {
	private ArrayList<Object> list = new ArrayList<>();

	public boolean isEmpty() { 
		return list.isEmpty();
	}

	public int getSize( ){ 
		return list.size();
	}

	public Object peek() {
		return list.get(getSize() - 1);
	}

	public Object pop() {
		Object o = list.get(getSize()-1); 
		list.remove(getSize()-1); 
		return o; 
	}

	public void push(Object o) { 
		list.add(o);
	}

	@Override
	public String toString() {
		 StringBuilder sb = new StringBuilder();
	        while (getSize() > 0) {
	            sb.append(String.valueOf(pop()));
	        }
	        return "Stack: " + sb.toString();
	}
}

输出结果:

Stack: HenryKenSeanKevin 
11.11 (对 ArrayList 排序)

编写以下方法,对一个数值的 ArrayList 进行排序:

public static void sort(ArrayList<Integer> list)

编写测试程序,提示用户输人 5 个数字,将其存储在一个数组列表中,并且以升序进行 显不。

import java.util.ArrayList;
import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter five integers: ");
        ArrayList<Integer> list = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            list.add(in.nextInt());
        }

        sort(list);
        System.out.print("The numbers in increasing order: ");
        System.out.print("\n" + list.toString());
        in.close();
    }

    public static void sort(ArrayList<Integer> list) {
        boolean loop = true;
        while (loop) {
            loop = false; //Reset to check if can remain false
            for (int n = 0; n < list.size(); n++) {
                for (int i = n; i < list.size(); i++) {
                    if (!(i == n)) {
                        if (list.get(n) > list.get(i)) {
                            loop = true; // Not finished sorting..
                            swapElements(list, n, i);
                        }

                    }
                }
            }

        }


    }

    static void swapElements(ArrayList<Integer> list, int idx1, int idx2) {
        Integer temp = list.get(idx1);
        list.set(idx1, list.get(idx2));
        list.set(idx2, temp);
    }
}

输出结果:

Enter five integers: 1 4 77 6 2
The numbers in increasing order: 
[1, 2, 4, 6, 77]
11.12 (对 ArrayList 求和)

编写以下方法,返回 ArrayList 中所有数字的和:

public static double sum(ArrayList<Double> list)

编写测试程序,提示用户输人 5 个数字,将其存储在一个数组列表中,并且显示它们的和。

import java.util.ArrayList;

public class Test {
    public static void main(String[] args) {
        ArrayList<Double> list = new ArrayList<>();
        list.add(4.0);
        list.add(3.0);
        list.add(2.0);
        list.add(1.0);
        System.out.println(sum(list));
    }
    
    public static double sum(ArrayList<Double> list) {
    	double sum = 0;
    	for (int i = 0; i < list.size(); i++) {
    		sum = sum + list.get(i);
    	}
    	return sum;
    }
}
10.0
*11.13 (去掉重复元素)

使用下面的方法头编写方法,从一个整数的数组列表中去掉重复元素:

public static void removeDuplicate(ArrayList<Integer> list)

编写测试程序,提示用户输人 10 个整数到列表中,显示其中不同的整数,并以一个空格分隔的方式来进行显示。

import java.util.ArrayList;

public class Test {
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<>();
        list.add(4);
        list.add(3);
        list.add(2);
        list.add(2);
        list.add(2);
        list.add(2);
        list.add(9);
        list.add(8);
        removeDuplicate(list);
        System.out.println(list.toString());
    }
    
    public static void removeDuplicate(ArrayList<Integer> list) {
    	//让首位循环去和首位+1去对比,如果相同,那么就移除首位+1
    	for (int i = 0; i < list.size() - 1; i++) {
    		for (int j = i + 1; j < list.size(); j++) {
    			if (list.get(i) == list.get(j)) {
    				list.remove(j);
    				j = j - 1;
    			}
    		}
    	}
    }
}

输出结果:

[4, 3, 2, 9, 8]
11.14 (结合两个列表)

使用下面的方法头编写一个方法,返回两个数组列表的并集。

public static ArrayList<Integer> union(ArrayList<Integer> list1, ArrayList<Integer> list2)

例如,两个数组列表 {2,3,1,5} 和 {3,4,6} 的并集为 {2,3,1,5,3,4,6} 。编写测试程序,提示用户输入两个列表,每个列表有 5 个整数,然后显示它们的并集。输出中,以一个空格进行分隔。

import java.util.ArrayList;

public class Test {
    public static void main(String[] args) {
        ArrayList<Integer> list1 = new ArrayList<>();
        ArrayList<Integer> list2 = new ArrayList<>();
        list1.add(4);
        list1.add(3);
        list1.add(2);
        list1.add(2);
        list2.add(2);
        list2.add(4);
        list2.add(8);
        list2.add(9);
        System.out.println(union(list1, list2));
    }
    
    public static ArrayList<Integer> union(ArrayList<Integer> list1, ArrayList<Integer> list2) {
    	for (int i = 0; i < list2.size(); i++) {
    		list1.add(list2.get(i));
    	}
    	return list1;
    }
}
[4, 3, 2, 2, 2, 4, 8, 9]
*11.15(凸多边形面积)

如果一个多边形中连接任意两个顶点的线段都包含在多边形中,则称为凸多边形。编写一个程序,提示用户输人一个凸多边形中的顶点数,并顺时针输入点,然后程序显示多边形的面积信息。这里是一个程序的运行示例:

import java.util.ArrayList;
import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        System.out.print("Enter the number of points: ");
        int numPoints = in.nextInt();

        ArrayList<double[]> pts = new ArrayList<>();

        System.out.print("Enter the coordinates of the points in the convex polygon: ");

        for (int i = 0; i < numPoints; i++) {
            double[] pt = new double[2];
            for (int xy = 0; xy < 2; xy++) {
                pt[xy] = in.nextDouble();
            }
            pts.add(pt);
        }

        System.out.print("The area of the convex polygon is ");
        System.out.println(getAreaConvexPolygon(pts) + "");

        in.close();

    }

    static double getAreaConvexPolygon(ArrayList<double[]> pts) {
        double[] lastPoint = pts.get(pts.size() - 1);
        double[] firstPoint = pts.get(0);
        double operand1 = lastPoint[0] * firstPoint[1]; // xn * y1
        for (int i = 0; i < pts.size() - 1; i++) {
            double[] pt = pts.get(i);
            double[] nextPt = pts.get(i + 1);
            operand1 += pt[0] * nextPt[1]; // x1 * y2 + x2 * y3 + x(n) * y(n+1) + {x(n) * y1}
        }
        double operand2 = lastPoint[1] * firstPoint[0]; // yn * x1
        for (int i = 0; i < pts.size() - 1; i++) {
            double[] pt = pts.get(i);
            double[] nextPt = pts.get(i + 1);
            operand2 += pt[1] * nextPt[0]; // y1 * x2 + y2 * x3 + y(n) + x(n+1) + {y(n) * x1}

        }
        return Math.abs((operand1 - operand2) * 0.5);

    }

}

输出结果:

Enter the number of points: 7
Enter the coordinates of the points in the convex polygon: -12 0 -8.5 10 0 11.4 5.5 7.8 6 -5.5 0 -7 -3.5 -13.5
The area of the convex polygon is 292.575
**11.16(加法测试)

重写程序清单5-1,如果用户重复输入了相同的答案,则给出用户警告。

import java.util.ArrayList;
import java.util.Scanner;

public class Test {
	public static void main(String[]args) { 
		ArrayList<Integer> list = new ArrayList<>();
		Scanner input = new Scanner(System.in);
		int number1 = (int)(Math.random() * 10); 
		int number2 = (int)(Math.random() * 10);
		System.out.print("What is " + number1 + " + " + number2 + "? ");
		int answer = input.nextInt();
		
		while (number1 + number2 != answer) {
			if (list.contains(answer)) {
				 System.out.println("You've already entered " + answer);
	             System.out.print("Try again. What is " + number1 + " + " + number2 + "? ");
	             answer = input.nextInt();
			}
			else {
				System.out.print("Wrong answer. Try again. What is " + number1 + " + " + number2 + "? ");
				answer = input.nextInt();
				list.add(answer);
			}
		}
		System.out.println("You got it!");
	}
}

输出结果:

What is 8 + 8? 5
Wrong answer. Try again. What is 8 + 8? 5
You've already entered 5
Try again. What is 8 + 8? 16
You got it!
**11.17 (代數 :完全平方)

编写一个程序,提示用户输人一个整数m, 然后找到最小的整数n, 使得 m*n 是一个完全平方。

import java.util.ArrayList;
import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter an integer: ");
        int m = in.nextInt();

        int n = findN(findSmallestFactors(m));
        System.out.println("The smallest number n for m * n to be a perfect square is " + n);
        System.out.println("m * n is " + m * n);

    }

    static ArrayList<Integer> findSmallestFactors(int m) {

        ArrayList<Integer> smallFactors = new ArrayList<>();

        for (int f = 2; m != 1; f++) {
            if (m % f == 0) {
                smallFactors.add(f);
                m /= f;
                f = 1; // Reset the test factor
            }
        }
        return smallFactors;
    }

    static Integer findN(ArrayList<Integer> factors) {
        ArrayList<Integer> oddCounts = new ArrayList<>();
        for (int i = 0; i < factors.size(); i++) {
            int num = factors.get(i);
            int count = 0;
            for (Integer integer : factors) {
                if (integer == num) {
                    count++;
                }
            }
            if (count % 2 != 0 && !oddCounts.contains(num)) {
                oddCounts.add(num);
            }

        }

        Integer result = 1;
        for (Integer oddCount : oddCounts) {
            result *= oddCount;
        }
        return result;
    }

}

输出结果:文章来源地址https://www.toymoban.com/news/detail-462780.html

Enter an integer: 90
The smallest number n for m * n to be a perfect square is 10
m * n is 900

到了这里,关于《Java黑皮书基础篇第10版》 第11章【习题】的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【C语言】练习题整理:11

    今天是10道选择题 下面代码段的输出结果是: -12 自右至左的结合方向称为“右结合性”。最典型的右结合 性运算符是赋值运算符。 如x=y=z,由于“=”的右结合性,应先执行y=z,再执行x=(y=z)运算。 C语言运算符中有不少为右结合性,应注意区别,以避免理解错误。 计算顺序是

    2024年02月11日
    浏览(39)
  • Java 语言程序设计(基础篇)原书第10版 梁勇著 PDF 文字版电子书

    Java 语言程序设计(基础篇)原书第 10 版 是 Java 语言的经典教材,中文版分为基础篇和进阶篇,主要介绍程序设计基础、面向对象程序设计、GUI 程序设计、数据结构和算法、高级 Java 程序设计等内容。本书通过示例讲解问题求解技巧,提供大量的程序清单,每章配有丰富的

    2024年04月16日
    浏览(33)
  • C++编程最基础练习题(1-10) 小白入门必刷

    C++编程练习题 (1-10) 1. 输入3个数,求最大值 2. 编程序,求方程ax2+bx+c=0的根 3. 输入一个成绩,打印相应的等级 4. 输入3个double类型的值,判断这3个值是否可以表示一个三角形的三条边 5. 输入20个数,求其最大、最小和平均值 6. 输入若干个数,设输入的第一个数为后面要输

    2023年04月19日
    浏览(87)
  • C语言基础习题讲解

    1. 设计一个程序, 输入三位数a, 分别输出个,十,百位. (0a1000) 样例输入: 251 样例输出: 2 5 1 2. 设计一个程序, 输入整数l, 求边长为l的正方形面积, 比直径为l的圆形面积大多少. (0l1000, PI取3.14, 输出结果保留两位小数) 样例输入: 3 样例输出: 1.93 1. 设计一个程序, 输入a,b,c三个整数,

    2024年02月07日
    浏览(21)
  • 【R语言编程基础】【课后习题答案】【全】

    (1)多行注释的快捷键是(C)。 A.Ctrl+Shin+N B.Ctrl+N C.Ctrl+Shin+C D.Ctrl+C (2)以下函数不能直接查看plot函数的帮助文档的是(B)。 A. ?plot B.??plot C.help(plot) D.help(plot) (3)以下R包的加载方式正确的是(A)。 A.install.package 函数 B.library 函数 C…libPaths 函数 D.install 函数 (4)以下R包中不

    2023年04月08日
    浏览(40)
  • 编译原理1.6习题 程序设计语言基础

    图源:文心一言 编译原理习题整理~🥝🥝 作为初学者的我,这些习题主要用于自我巩固。由于是自学,答案难免有误,非常欢迎各位小伙伴指正与讨论!👏💡 第1版:自己的解题,与AI老师的判卷~🧩🧩 编辑: 梅头脑🌸  审核: 文心一言 题源: 龙书《编译原理》 Alfre

    2024年01月19日
    浏览(39)
  • 2.如何选择go语言基础类型——Leetcode习题9

    目录 本篇前瞻 Leetcode习题9 题目描述 原题解析 代码编写 有符号整形 基本数据类型 整形 有符号整形 无符号整形 浮点型 布尔型 字符 本篇小结 下一篇预告 欢迎来go语言的基础篇,这里会帮你梳理一下go语言的基本类型,注意本篇有参考go圣经,如果你有完整学习的需求可以看

    2024年02月12日
    浏览(36)
  • Java基础习题大全

    下列哪个是JDK提供的编译器? A.java.exe B.javac.exe C.javap.exe D.javaw.exe 下列哪个是Java应用程序主类中正确的main方法? A.public void main (String args[ ]) B.static void main (String args[ ]) C.public static void Main (String args[]) D.public static void main (String args[ ]) 下列哪个叙述是正确的? A.Java源文件是由若干

    2024年02月12日
    浏览(28)
  • C语言循环结构一些重要的练习题(较为基础的)

    循环结构 1.求累加和问题 2.输出字母A-Z 3.输入正整数n,计算并输出n! 4.将一个正整数倒序输出 5.打印九九乘法表 6.输出三角形、菱形 7.continue语句和break语句 8.输出100-200之间不能被3整除的数 9.求Pi的值,根据 10.求斐波那契数列前k项的值 11.判断一个数是否为素数 12.输出特定

    2023年04月08日
    浏览(28)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包