Java语言程序设计(第3版)沈泽刚主编第10,11,12章课后习题答案
第10章 接口和Lambda表达式
10.1 定义Duck类实现Swimmable接口和flyable接口。
interface Swimmable{
public void swim() ;
}
interface flyable{
public void fly() ;
}
public class Duck implements Swimmable, flyable{
@Override
public void swim() {
System.out.println("I can swimming") ;
}
@Override
public void fly() {
System.out.println("I can fly") ;
}
public static void main(String[] args){
Duck duck = new Duck() ;
duck.fly() ;
duck.swim() ;
Swimmable s = duck ; //向上转换,自动类型转换
s.swim() ;
Duck d = (Duck)s ; //向下转换,强制类型转换
d.fly() ;
d.swim() ;
}
}
10.2 定义一个名为RandomIntSequence的类实现IntSequence接口。
interface IntSequence{
public boolean hasNext() ;
public int next() ;
}
public class RandomIntSequence implements IntSequence{
private int n ;
@Override
public boolean hasNext() {
n = (int)(Math.random() * 90 + 10) ;
return true;
}
@Override
public int next() {
return n;
}
public static void main(String[] args){
RandomIntSequence r = new RandomIntSequence() ;
if(r.hasNext()){
System.out.println(r.next()) ;
}
}
}
10.3 设计一个名为SequenceTest的类,在其中编写一个static方法用于计算一个整数n的平均值
public class SequenceTest {
public static double average(IntSequence seq, int n){
double sum = 0.0 ;
int m = n ;
while(seq.hasNext() && m > 0){
sum += seq.next() ;
m -- ;
}
return sum / n ;
}
public static void main(String[] args){
RandomIntSequence r = new RandomIntSequence() ;
double ave = average(r, 10) ;
System.out.println(ave) ;
}
}
10.5 修改Employee的定义,让根据员工年龄进行比较
public class Employee implements Comparable<Employee>{
int id ;
int age ;
double salary ;
String name ;
public Employee(int id, String name, int age, double salary){
this.id = id ;
this.age = age ;
this.salary = salary ;
this.name = name ;
}
@Override
public int compareTo(Employee employee) {
return employee.age - this.age ;
}
public String toString(){
return "id = " + id + " name = " + name + " age = " + age + " salary = " + salary ;
}
public static void main(String[] args){
Employee [] employees = new Employee[]{new Employee(1, "张三", 12, 2200), new Employee(2, "李四", 23, 2300)} ;
if(employees[0].compareTo(employees[1]) <= 0){
System.out.println(employees[0]) ;
System.out.println(employees[1]) ;
}else{
System.out.println(employees[1]) ;
System.out.println(employees[0]) ;
}
}
}
10.6 用compareTo()方法计算连个面积之差
public class Circle implements Comparable<Circle>{
double radius ;
public Circle(double radius){
this.radius = radius ;
}
public double getArea(){
return Math.PI * radius * radius ;
}
@Override
public int compareTo(Circle circle) {
return (int)(circle.getArea() - getArea());
}
public static void main(String[] args){
Circle [] circles = new Circle[]{new Circle(1.0), new Circle(2.0), new Circle(3.0)} ;
System.out.println(circles[0].compareTo(circles[1])) ;
}
}
10.7 设计一个Position类,该类有两个成员变量x,y表示坐标。
public class Position implements Comparable<Position> {
int x ;
int y ;
public Position(int x, int y){
this.x = x ;
this.y = y ;
}
@Override
public int compareTo(Position o) {
double dist1 = Math.sqrt(x*x + y*y) ;
double dist2 = Math.sqrt(o.x*o.x +o.y*o.y) ;
return (int)(dist1 - dist2);
}
public static void main(String[] args){
Position position1 = new Position(1, 2) ;
Position position2 = new Position(2,4) ;
System.out.println(position1.compareTo(position2)) ;
}
}
11.8 实现Student对象按姓名排序。
import java.util.Arrays;
import java.util.Comparator;
class Comp implements Comparator<Student> {
@Override
public int compare(Student o1, Student o2) {
if(o1.name.compareTo(o2.name) > 0){
return 1 ;
}else if(o1.name.compareTo(o2.name) < 0){
return -1 ;
}else{
return 0 ;
}
}
}
public class Student implements Comparable<Student>{
int id ;
String name ;
public Student(int id, String name){
this.id = id ;
this.name = name ;
}
@Override
public int compareTo(Student o) {
return this.id - o.id;
}
public String toString(){
return "id = " + id + " name = " + name ;
}
public static void main(String[] args){
Student [] student = new Student[]{new Student(1,"李四"), new Student(2, "张三"), new Student(3, "王五")} ;
Arrays.sort(student, new Comp()) ;
for(Student s : student){
System.out.println(s) ;
}
}
}
10.9 编写程序,对字符串数组进行降序排序。
import java.util.Arrays;
import java.util.Comparator;
public class DescSort implements Comparator<String> {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
public static void main(String[] args){
String [] s = new String[] {"google", "bai du", "sou hu"} ;
Arrays.sort(s, new DescSort()) ;
for(String s1 : s){
System.out.println(s1) ;
}
}
10.12 使用Lambda表达式实现calculate()方法。
interface Calculate{
public double calculate(double a, double b) ;
}
public class CalculatorDemo {
public static void main(String[] args){
Calculate c = (a, b) -> Math.pow(a,2) + Math.pow(b,2) ;
int a = 10 ;
int b = 20 ;
System.out.println(c.calculate(a,b)) ;
}
}
第11章 泛型与集合
11.1
public class Point<T> {
T x, y ;
public Point(T x, T y){
this.x = x ;
this.y = y ;
}
public void setX(T x){
this.x = x ;
}
public T getX(){
return x ;
}
public void setY(T y){
this.y = y ;
}
public T getY(){
return y ;
}
public void translate(T x, T y){
this.x = x ;
this.y = y ;
}
public String toString(){
return "x = " + x + " y = " + y ;
}
public static void main(String[] args){
Point<Integer> point1 = new Point<>(1, 2) ;
Point<Double> point2 = new Point<>(3.0,4.0) ;
point1.translate(5, 6);
System.out.println(point1) ;
System.out.println(point2) ;
}
}
11.4 创建一个ArrayList对象,在其中添加若干元素,
编写程序,使用3种方法将每个字符转换成大写。
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class UpperCaseDemo {
public static void main(String[] args){
List<String> list = new ArrayList<>() ;
String [] s = {"google", "bai du", "zi jie"} ;
for(int i=0; i<s.length; i++){
list.add(s[i]) ;
}
for(int i=0; i<list.size(); i++){
String name = list.get(i) ;
name = name.toUpperCase() ;
list.set(i, name);
}
System.out.println(list) ;
List<String> list1 = Arrays.asList(s) ;
Iterator iterator = list1.iterator() ;
while(iterator.hasNext()){
String name = (String)iterator.next() ;
name = name.toUpperCase() ;
System.out.print(name + " ") ;
}
list1.replaceAll(String::toUpperCase);
System.out.println(list1) ;
}
}
11-5 编写程序,将一个字符串中的单词解析出来,然后将它们添加到一个HashSet中, 并输出每个重复的单词,不同单词的个数,消除重复单词后的列表。
import java.util.HashSet;
import java.util.Set;
public class FindDump {
public static void main(String[] args){
String s = "I can I come I fly" ;
Set<String> unique = new HashSet<>() ;
Set<String> dump = new HashSet<>() ;
String [] array = s.split(" ") ;
for(String s1 : array){
if(!unique.add(s1)){
dump.add(s1) ;
}
}
System.out.println("重复的单词:" + dump) ;
System.out.println("不同单词的个数:" + unique.size()) ;
System.out.println("消除重复单词后的列表:" + unique) ;
}
}
11.6 编写程序,随机生成10个两位整数,将其分别存入HashSet和TreeSet对象, 然后将他们输入,观察输出结果的不同。
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
public class SetDemo {
public static void main(String[] args){
Set<Integer> hashSet = new HashSet<>() ;
Set<Integer> treeSet = new TreeSet<>() ;
for(int i=0; i<10; i++){
int num = (int)(Math.random() * 10 + 90) ;
hashSet.add(num) ;
treeSet.add(num) ;
}
System.out.println(hashSet) ; //无序不重复
System.out.println(treeSet) ; //有序不重复
}
}
11-7 编写程序,实现一个对象栈类,要求利用ArrayList类实现该栈。
import java.util.ArrayList;
public class MyStack <T> {
private ArrayList<T> list ;
public MyStack(){
list = new ArrayList<T>() ;
}
public boolean isEmpty(){
return list.isEmpty() ;
}
public int getSize(){
return list.size() ;
}
public T peek(){
return list.get(0) ;
}
public T pop(){
return list.remove(0) ;
}
public void push(T t){
list.add(0, t) ;
}
public int search(T t){
return list.indexOf(t) ;
}
public static void main(String[] args){
MyStack<Integer> list = new MyStack<>() ;
list.push(new Integer(1)) ;
list.push(new Integer(2)) ;
list.push(new Integer(3)) ;
System.out.println(list.getSize()) ;
System.out.println(list.isEmpty()) ;
System.out.println(list.pop()) ;
System.out.println(list.peek()) ;
System.out.println(list.search(1)) ;
}
}
11.8 假设Employee类包含一个int成员id,如果要求Employee可以按id值比较大小,创建几个Employee对象,将它们存储到TreeSet中。
import java.util.Set;
import java.util.TreeSet;
public class Employee implements Comparable<Employee> {
public int id ;
public String name ;
public Employee(int id, String name){
this.id = id ;
this.name = name ;
}
@Override
public int compareTo(Employee employee) {
return this.id - employee.id;
}
public String toString(){
return "id = " + id + " name = " + name ;
}
public static void main(String[] args){
Employee [] employees = new Employee[3] ;
employees[0] = new Employee(1, "王国栋") ;
employees[1] = new Employee(3, "唐乃乔") ;
employees[2] = new Employee(2, "张珂珂") ;
Set<Employee> ts = new TreeSet<>() ;
ts.add(employees[0]) ;
ts.add(employees[1]) ;
ts.add(employees[2]) ;
for(Employee emp : ts){
System.out.println(emp) ;
}
}
}
11.9 编写程序,实现一个PriorityQueue对象,将整形数组元素插入队列,然后输出并观察结果。
import java.util.PriorityQueue;
import java.util.Queue;
public class PQDemo {
public static void main(String[] args){
Queue<Integer> queue = new PriorityQueue<>() ;
Integer [] array = {1, 5, 3, 7, 6, 9, 8} ;
for(int i=0; i<array.length; i++){
queue.add(array[i]) ;
}
while(!queue.isEmpty()){
System.out.println(queue.poll()) ;
}
}
}
11.10 编写程序,生成一个包含1000个随机生成的3位数的流,过滤该流,使其仅能包含被7整除或者含有7的数,输出这些数和个数。
import java.util.stream.IntStream;
public class IntStreamDemo {
public static void main(String[] args){
int [] nums = new int [1000] ;
for(int i=0; i<nums.length; i++){
nums[i] = (int )(Math.random() * 900 + 100);
}
IntStream stream = IntStream.of(nums) ;
stream = stream.filter(n -> ((n % 7 == 0) || (n % 10 == 7) || ((n / 10) % 10 == 7)) || (n / 100 == 7)) ;
int [] result = stream.toArray() ;
for(int i=0; i<result.length; i++){
System.out.println(result[i]) ;
}
System.out.println("满足条件的个数:" + result.length) ;
}
}
11.11 编写程序,分别使用顺序流和并行流计算10,20,30,40这几个数字的阶乘, 输出结果及完成计算的时间,使用并行流是否比顺序流更快。
import java.math.BigInteger;
import java.time.Duration;
import java.time.Instant;
import java.util.Arrays;
import java.util.List;
public class ParallelStreamDemo {
public static BigInteger factorial(long n){
BigInteger result = new BigInteger("1") ;
for(int i=1; i<=n; i++){
result = result.multiply(new BigInteger(i + "")) ;
}
return result ;
}
public static void main(String[] args){
List<Integer> list = Arrays.asList(10, 20, 30, 40) ;
Instant begin = Instant.now() ;
list.parallelStream().map(n -> (factorial(n))).forEach(System.out::println);
Instant end = Instant.now() ;
System.out.println("使用并行流使用时间:" + Duration.between(begin, end).toMillis()+ "毫秒") ;
Instant begin1 = Instant.now() ;
list.stream().map(n ->(factorial(n))).forEach(System.out::println);
Instant end1 = Instant.now() ;
System.out.println("使用顺序流使用时间:" + Duration.between(begin1, end1).toMillis() + "毫秒") ;
}
}
第12章 异常处理
12.1
import java.util.InputMismatchException;
import java.util.Scanner;
public class Test {
public static void main(String[] args){
try {
Scanner input = new Scanner(System.in) ;
System.out.print("请输入一个double型的圆形半径:") ;
double radius = input.nextDouble();
System.out.println("圆形的面积为:" + Math.PI * radius * radius) ;
}catch(InputMismatchException e){
System.out.println(e) ;
System.out.println("输入格式不正确") ;
}
}
}
12.2 提示用户输入两个整数,然后显示它们的和,程序应该在输入不正确时,提示用户再次读取数字。
import java.util.InputMismatchException;
import java.util.Scanner;
public class ExceptionDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean continueInput = true;
while (continueInput)
try {
System.out.print("请输入两个整数:");
int a = input.nextInt();
int b = input.nextInt();
int sum = a + b;
continueInput = false;
System.out.println("a + b = " + sum);
} catch (InputMismatchException e) {
System.out.println(e);
input.nextLine();
}
}
}
12.3 首先创建一个由100个随机选取的整数构成的数组,然后提示用户输入数组下标,程序显示对应元素的值,如果输入下标越界,则提示下标越界。
import java.util.Random;
import java.util.Scanner;
public class IndexDemo {
public static void main(String[] args){
Scanner input = new Scanner(System.in) ;
int [] array = new int [100] ;
Random random = new Random() ;
for(int i=0; i<array.length; i++){
array[i] = random.nextInt() ;
}
try{
System.out.print("请输入数组下标:") ;
int index = input.nextInt() ;
System.out.println(array[index]) ;
}catch(IndexOutOfBoundsException e){
System.out.println(e) ;
System.out.println("数组下标越界") ;
}
}
}
12.4 编写程序,在main()方法中使用try块抛出一个Exception类的对象,为Exception的构造方法提供一个字符串参数,在catch块内捕获该异常并打印字符串参数,添加一个finally块并打印一条信息。
public class Test4 {
public static void main(String[] args){
try{
throw new Exception("demo Exception") ;
}catch(Exception e){
System.out.println(e.getMessage()) ;
}finally{
System.out.println("Program finished") ;
}
}
}
12.5
import java.io.IOException;
public class Test5 {
public static void methodA() throws IOException{
System.out.println("A") ;
}
public static void methodB() throws IOException {
methodA() ;
System.out.println("B") ;
}
public static void main(String[] args){
try {
methodB();
}catch(IOException e){
System.out.println(e) ;
}finally{
System.out.println("Program finished") ;
}
}
}
12.6 创建一个自定义的异常类,该类继承Exception类
public class MyException extends Exception{
private String param ;
public MyException(String param){
super(param) ;
}
public void output(){
System.out.println(getMessage()) ;
}
public static void main(String[] args){
try{
throw new MyException("My Exception") ;
}catch(MyException e){
e.output();
System.out.println(e.getMessage()) ;
}
}
}