JAVA语言程序设计基础篇(Chapter 11)课后习题参考答案

一. 简答题(共6题,100分)

1. (简答题, 15分)

(The Triangle class) Design a class named Triangle that extends GeometricObject . The class contains:

■ Three double data fields named side1 , side2 , and side3 with default values 1.0 to denote three sides of the triangle.

■ A no-arg constructor that creates a default triangle.

■ A constructor that creates a triangle with the specified side1 , side2 , and side3 .

■ The accessor methods for all three data fields.

■ A method named getArea() that returns the area of this triangle.

■ A method named getPerimeter() that returns the perimeter of this triangle.

■ A method named toString() that returns a string description for the triangle.

The toString() method is implemented as follows:

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

Draw the UML diagrams for the classes Triangle and GeometricObject and implement the classes. Write a test program that prompts the user to enter three sides of the triangle, a color, and a Boolean value to indicate whether the triangle is filled. The program should create a Triangle object with these sides and set the color and filled properties using the input. The program should display the area, perimeter, color, and true or false to indicate whether it is filled or not.

Please submit the source code in the text form,and attach pictures to show the output of your program, and the UML graphical notations for the  classes Triangle and GeometricObject.

import java.util.Date;
import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Please input three sides for this triangle:");
        double s1 = sc.nextDouble();
        double s2 = sc.nextDouble();
        double s3 = sc.nextDouble();

        System.out.println("Please input this triangle's color:");
        String color = sc.next();
        System.out.println("Please input a boolean value (true : filled  ;  false : unfilled) :");
        Boolean flag = sc.nextBoolean();
        sc.close();
        Triangle triangle = new Triangle(s1, s2, s3, color, flag);
        System.out.println(triangle.toString());
        System.out.println("The triangle's area is " + triangle.getArea());
        System.out.println("The triangle's perimeter is " + triangle.getPerimeter());
        System.out.println("The triangle's color is " + triangle.getColor());
        System.out.println("The triangle's is filled : " + triangle.isFilled());
    }
}

class GeometricObject {
    private String color = "white";
    private boolean filled;
    private Date dateCreated;

    public GeometricObject() {
        this.dateCreated = new Date();
    }

    public GeometricObject(String color, boolean filled) {
        this.color = color;
        this.filled = filled;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public boolean isFilled() {
        return filled;
    }

    public void setFilled(boolean filled) {
        this.filled = filled;
    }

    public Date getDateCreated() {
        return dateCreated;
    }

    @Override
    public String toString() {
        return "GeometricObject{" +
                "color='" + color + '\'' +
                ", filled=" + filled +
                ", dateCreated=" + dateCreated +
                '}';
    }
}

class Triangle extends GeometricObject {
    private double side1 = 1.0;
    private double side2 = 1.0;
    private double side3 = 1.0;

    public Triangle() {
    }

    public Triangle(double side1, double side2, double side3, String color, boolean filled) {
        super(color, filled);
        this.side1 = side1;
        this.side2 = side2;
        this.side3 = side3;
    }

    public double getSide1() {
        return side1;
    }


    public double getSide2() {
        return side2;
    }

    public double getSide3() {
        return side3;
    }


    public double getArea() {
        double p = (side1 + side2 + side3) / 2;
        double area = Math.sqrt(p * (p - side1) * (p - side2) * (p - side3));
        return area;
    }

    public double getPerimeter() {
        return side1 + side2 + side3;
    }

    @Override
    public String toString() {
        return "Triangle:" +
                "side1 = " + side1 +
                ", side2 = " + side2 +
                ", side3 = " + side3;
    }
}

 

2. (简答题, 15分)

(The Person , Student , Employee , Faculty , and Staff classes) Design a class named Person and its two subclasses named Student and Employee . Make Faculty and Staff subclasses of Employee . A person has a name, address, phone number, and email address. A student has a class status (freshman, sophomore, junior, or senior). Define the status as a constant. An employee has an office, salary, and date hired. A faculty member has office hours and a rank. A staff member has a title. Override the toString method in each class to display the class name and the person's name.

Draw the UML diagram for the classes and implement them. Write a test program that creates a Person , Student , Employee , Faculty , and Staff , and invokes their toString() methods.

Please submit the source code in the text form,and attach pictures to show the output of your program, and the UML graphical notations for the  classes  Person , Student , Employee , Faculty , and Staff.

public class Demo1 {
    public static void main(String[] args) {
        Person person = new Person("Mike", "A Street", "123456", "123456@qq.com");
        Person student = new Student(1, "Jack", "B Street", "123456", "123456@edu.com");
        Person employee = new Employee("C office", 5000, new MyDate(2022, 5, 1), "Bob", "C street", "123456", "123456@gov.com");
        Person faculty = new Faculty(8, "CTO", "D office", 10000, new MyDate(2022, 5, 1), "John", "D Street", "123456", "123456@ofi.com");
        Person staff = new Staff("Best staff", "E office", 4000, new MyDate(2022, 1, 1), "Philip", "E Street", "123456", "123456@stf.com");
        System.out.println(person.toString());
        System.out.println();
        System.out.println(student.toString());
        System.out.println();
        System.out.println(employee.toString());
        System.out.println();
        System.out.println(faculty.toString());
        System.out.println();
        System.out.println(staff.toString());
    }

}

class Person {
    private String name;
    private String address;
    private String phone;
    private String email;

    public Person(String name, String address, String phone, String email) {
        this.name = name;
        this.address = address;
        this.phone = phone;
        this.email = email;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    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;
    }

    @Override
    public String toString() {
        return "The Person's name is " + name + '\'' +
                ", address is " + address + '\'' +
                ", phone is " + phone + '\'' +
                ", email is " + email + '\'';
    }
}

class Student extends Person {
    private int classState;
    public final static int FRESHMAN = 1;
    public final static int SOPHOMORE = 2;
    public final static int JUNIOR = 3;
    public final static int SENIOR = 4;

    public Student(int classState, String name, String address, String phone, String email) {
        super(name, address, phone, email);
        this.classState = classState;
    }

    public int getClassState() {
        return classState;
    }

    public void setClassState(int classState) {
        this.classState = classState;
    }

    @Override
    public String toString() {
        return "The Student's classState is " + classState + '\n' + super.toString();
    }
}

class Employee extends Person {
    private String office;
    private double salary;
    private MyDate DateOfAppointment;

    public Employee(String office, double salary, MyDate dateOfAppointment, String name,
                    String address, String phone, String email) {
        super(name, address, phone, email);
        this.office = office;
        this.salary = salary;
        DateOfAppointment = dateOfAppointment;
    }

    public String getOffice() {
        return office;
    }

    public void setOffice(String office) {
        this.office = office;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    public String getDateOfAppointment() {

        return DateOfAppointment.getYear() + "Year" + DateOfAppointment.getMonth()
                + "Month" + DateOfAppointment.getDay() + "Day";

    }


    @Override
    public String toString() {
        return "The Employee's dateOfAppointment is " + getDateOfAppointment() +
                " ,office is " + office + '\'' +
                " ,salary is " + salary + '\n' + super.toString()
                ;
    }
}

class Faculty extends Employee {
    private long officeHours;
    private String rank;

    public Faculty(long officeHours, String rank, String office, double salary, MyDate dateOfAppointment, String name, String address,
                   String phone, String email) {
        super(office, salary, dateOfAppointment, name, address, phone, email);
        this.officeHours = officeHours;
        this.rank = rank;
    }

    public long getOfficeHours() {
        return officeHours;
    }

    public void setOfficeHours(long officeHours) {
        this.officeHours = officeHours;
    }

    public String getRank() {
        return rank;
    }

    public void setRank(String rank) {
        this.rank = rank;
    }

    @Override
    public String toString() {
        return "The Faculty's officeHours is " + officeHours +
                ", rank is " + rank + '\'' + '\n' +
                super.toString();
    }
}

class Staff extends Employee {
    private String title;

    public Staff(String title, String office, double salary, MyDate dateOfAppointment, String name, String address, String phone, String email) {
        super(office, salary, dateOfAppointment, name, address, phone, email);
        this.title = title;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    @Override
    public String toString() {
        return "The Staff's title is " + title + '\'' + '\n' +
                super.toString();
    }
}

class MyDate {

    private int year;
    private int month;
    private int day;

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

    public int getYear() {
        return year;

    }

    public int getMonth() {
        return month;

    }

    public int getDay() {
        return day;

    }

}

 

 

3. (简答题, 15分)

(Maximum element in ArrayList ) Write the following method that returns the maximum value in an ArrayList of integers. The method returns null if the list is null or the list size is 0 .

        public static Integer max(ArrayList<Integer> list)

Write a test program that prompts the user to enter a sequence of numbers ending with 0 , and invokes this method to return the largest number in the input.

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

public class Demo2 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        ArrayList<Integer> list = new ArrayList<>();
        System.out.println("Please input an ArrayList which is ended with 0 :");
        int value = sc.nextInt();
        while (value != 0) {
            list.add(value);
            value = sc.nextInt();
        }
        sc.close();
        System.out.println("The maximum element in ArrayList is " + max(list));
    }

    public static Integer max(ArrayList<Integer> list) {
        if (list.isEmpty() || list.size() == 0) {
            return null;
        } else {
            int max = list.get(0);
            int maxIndex = 0;
            for (int i = 0; i < list.size(); i++) {
                if (max < list.get(i)) {
                    max = list.get(i);
                    maxIndex = i;
                }
            }
            return max;
        }
    }
}

4. (简答题, 15分)

(The Course class) Rewrite the Course class in Listing 10.6 in the textbook. Use an ArrayList to replace an array to store students. Draw the new UML diagram for the class. You should not change the original contract of the Course class (i.e., the definition of the constructors and methods should not be changed, but the private members may be changed.)

Please submit the source code in the text form,and attach pictures to show the output of your program, and the UML graphical notation

import java.util.ArrayList;

public class Demo3 {
    public static void main(String[] args) {
        Course course = new Course("Programming");
        course.addStudent("Jack");
        course.addStudent("Mike");
        course.addStudent("John");
        course.addStudent("Bob");
        System.out.println("The number of students in this class is " + course.getNumberOfStudents());
        System.out.println("The students are:");
        System.out.println(course.getStudents());
        System.out.println();
        course.dropStudent("Bob");
        System.out.println("The number of students in this class is " + course.getNumberOfStudents());
        System.out.println("The students are:");
        System.out.println(course.getStudents());

    }
}

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

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

    public String getCourseName() {
        return courseName;
    }

    public void addStudent(String student) {
        students.add(student);
    }

    public void dropStudent(String student) {
        students.remove(student);
    }

    public ArrayList<String> getStudents() {
        return students;
    }

    public int getNumberOfStudents() {
        return numberOfStudents = students.size();
    }
}

.

5. (简答题, 20分)

(Largest rows and columns) Write a program that randomly fills in 0 s and 1 s into an n-by-n matrix, prints the matrix, and finds the rows and columns with the most 1 s. (Hint: Use two ArrayList s to store the row and column indices with the most 1 s.) Here is a sample run of the program:

     Enter the array size n: 4

     The random array is

     0011

     0011

     1101

     1010

     The largest row index: 2

     The largest column index: 2, 3

Please submit the source code in the text form,and attach a picture to show the output of your program.

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

public class Demo4 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the array size n:");
        int n = sc.nextInt();
        sc.close();
        System.out.println("The random array is ");
        int[][] array = new int[n][n];
        Random r = new Random();
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[i].length; j++) {
                array[i][j] = r.nextInt(2);
                System.out.print(" " + array[i][j] + " ");
            }
            System.out.println();
        }
        ArrayList<Integer> list1 = new ArrayList<>();
        int maxRow = 0;
        int maxIndex = 0;
        for (int j = 0; j < array[0].length; j++) {
            maxRow += array[0][j];
        }
        list1.add(maxIndex);
        for (int i = 1; i < array.length; i++) {
            int total = 0;
            for (int j = 0; j < array[i].length; j++) {
                total += array[i][j];
            }
            if (maxRow < total) {
                list1.clear();
                maxRow = total;
                maxIndex = i;
                list1.add(maxIndex);
            } else if (maxRow == total) {
                list1.add(i);
            }
        }
        System.out.print("The largest row index : ");
        for (int i = 0; i < list1.size(); i++) {
            if (i != (list1.size() - 1)) {
                System.out.print(list1.get(i) + ",");
            } else {
                System.out.print(list1.get(i));
            }
        }
        System.out.println();
        ArrayList<Integer> list2 = new ArrayList<>();
        int maxColumn = 0;
        int MaxIndex = 0;
        for (int i = 0; i < array.length; i++) {
            maxColumn += array[i][0];
        }
        list2.add(MaxIndex);
        for (int j = 1; j < array[0].length; j++) {
            int all = 0;
            for (int i = 0; i < array.length; i++) {
                all += array[i][j];
            }
            if (maxColumn < all) {
                list2.clear();
                maxColumn = all;
                MaxIndex = j;
                list2.add(MaxIndex);
            } else if (maxColumn == all) {
                list2.add(j);
            }
        }
        System.out.print("The largest column index : ");
        for (int i = 0; i < list2.size(); i++) {
            if (i != (list2.size() - 1)) {
                System.out.print(list2.get(i) + ",");
            } else {
                System.out.print(list2.get(i));
            }
        }
    }
}

6. (简答题, 20分)

(Remove duplicates) Write a method that removes the duplicate elements from an array list of integers using the following header:

    public static void removeDuplicate(ArrayList<Integer> list)

Write a test program that prompts the user to enter 10 integers to a list and displays the distinct integers separated by exactly one space. Here is a sample run:

     Enter ten integers: 34 5 3 5 6 4 33 2 2 4

     The distinct integers are 34 5 3 6 4 33 2

Please submit the source code in the text form,and attach a picture to show the output of your program.

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

public class Demo5 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        ArrayList<Integer> list = new ArrayList<>();
        int n;
        System.out.print("Enter ten integers: ");
        for (int i = 0; i < 10; i++) {
            n = sc.nextInt();
            list.add(n);
        }
        sc.close();
        removeDuplicate(list);

    }

    public static void removeDuplicate(ArrayList<Integer> list) {
        ArrayList<Integer> newList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            if (!newList.contains(list.get(i))) {
                newList.add(list.get(i));
            }
        }
        System.out.print("The distinct integers are");
        for (int i = 0; i < newList.size(); i++) {
            System.out.print(" " + newList.get(i));
        }
    }
}

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值