GVKun编程网logo

苏浪浪 201771010120《面向对象程序设计(java)》第六章学习总结(面向对象程序设计java答案)

3

对于想了解苏浪浪201771010120《面向对象程序设计的读者,本文将是一篇不可错过的文章,我们将详细介绍java》第六章学习总结,并且为您提供关于201771010106东文财《面向对象程序设计(

对于想了解苏浪浪 201771010120《面向对象程序设计的读者,本文将是一篇不可错过的文章,我们将详细介绍java》第六章学习总结,并且为您提供关于201771010106 东文财《面向对象程序设计(java)》 实验 6、201771010106 东文财《面向对象程序设计(java)》 实验 8、201771010106 东文财《面向对象程序设计(java)》实验 10、201771010106 东文财《面向对象程序设计(java)》实验 9的有价值信息。

本文目录一览:

苏浪浪 201771010120《面向对象程序设计(java)》第六章学习总结(面向对象程序设计java答案)

苏浪浪 201771010120《面向对象程序设计(java)》第六章学习总结(面向对象程序设计java答案)

第五章

主要学习OOP另一个部分----继承,继承使程序员可以使用现有的类,并根据需要进行修改。这是Java程序设计中的一个基础设计。

1.类、超类和子类; 

(1) 已有类称为:超类(superclass)、基类(base class) 或父类(parent  class)

新类称作:子类(subclass)、派生类(derived  class)或孩子类(child class)

(2).super是一个指示编译器调用超类方法的特有关键字,它不是一个对象的引用,不能将super赋给另一个对象变量

注:Java不支持多继承。

(3).多态性:多态性泛指在程序中同一个符号在不同的情况 下具有不同解释的现象。

(4). 不允许继承的类称为final类,在类的定义中用final修饰符加以说明

(5).抽象类:抽象方法充当着占位的角色,它们的具体实现在子类中。(  抽象类不能被实例化,即不能创建对象,只能产生子类。)

2.Object:所有类的超类;

1. Object类是Java中所有类的始祖——每一个类都由它扩展而来。

2.可以使用类型为Object的变量指向任意类型的对象。但要对它们进行专门的操作都要进行类型转换。

3. Object类中的equals方法用于测试某个对象是否同另一个对象相等。

4. Object类中的hashCode方法导出某个对象的散列码。散列码是任意整数,表示对象的存储地址。

两个相等对象的散列码相等。

3.泛型数组列表;

1. Java中,利用ArrayList类,可允许程序在运行时确定数组的大小。.

2.ArryList是一个采用类型参数的泛型类。为指定数组列表保存元素的对象类型,需要用一对尖括号将数组元素对象类名括起来加在后面。

ArryList<Employee> staff=new ArrayList<Employee>();

4.对象包装器和自动打包;

1. 所有基本数据类型都有着与之对应的预定义类,它们被称为对象包装器。

2. 对象包装器类是不可变的,即一旦构造了包装器,就不允更改包装在其中的值。且对象包装器类还是final,因此不能定义它们的子类。

3. 在JavaSE5.0中,可以自动的将基本数据类型转换为包装器类的对象,将这种变换称为自动打包

5.参数数量可变的方法;

1 在Java SE 5.0以前的版本中,每个Java方法都有固定数量的参数。然而,现在的版本提供了可以用可变的参数数量调用的方法(称为“可变参 ”方法)。

2. 用户自己可以定义可变参数的方法,并将参数指定为任意类型,甚至是基本类型。

6.枚举类;

1. 声明枚举类

 publicenumGrade{A,B,C,D,E};

它包括一个关键字enum,一个新枚举类型的名字 Grade以及为Grade定义的一组值,这里的值既非整型,亦非字符型。

2. 枚举类是一个类,它的隐含超类是java.lang.Enum。

3枚举值并不是整数或其它类型,是被声明的枚举类的自身实例

1、实验目的与要求

(1) 理解继承的定义;

(2) 掌握子类的定义要求

(3) 掌握多态性的概念及用法;

(4) 掌握抽象类的定义及用途;

(5) 掌握类中4个成员访问权限修饰符的用途;

(6) 掌握抽象类的定义方法及用途;

(7)掌握Object类的用途及常用API;

(8) 掌握ArrayList类的定义方法及用法;

(9) 掌握枚举类定义方法及用途。

2、实验内容和步骤

实验1: 导入第5章示例程序,测试并进行代码注释。

测试程序1:

Ÿ   在elipse IDE中编辑、调试、运行程序5-1 (教材152页-153页) ;

Ÿ   掌握子类的定义及用法;

Ÿ   结合程序运行结果,理解并总结OO风格程序构造特点,理解Employee和Manager类的关系子类的用途,并在代码中添加注释。

ManagerTest:类:

package inheritance;

/**
 * This program demonstrates inheritance.
 * @version 1.21 2004-02-21
 * @author Cay Horstmann
 */
public class ManagerTest
{
   public static void main(String[] args)
   {
      // 构建管理器对象
      Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15);
      boss.setBonus(5000);

      Employee[] staff = new Employee[3];

      // 用Manager和Employee对象填充staff数组

      staff[0] = boss;
      staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
      staff[2] = new Employee("Tommy Tester", 40000, 1990, 3, 15);

      // 打印所有Employee对象的信息
      for (Employee e : staff)
         System.out.println("name=" + e.getName() + ",salary=" + e.getSalary());
   }
}

employee类:

1 package inheritance;
 2 
 3 import java.time.*;
 4 
 5 public class Employee
 6 {
 7    private String name;//构建三个私有对象
 8    private double salary;
 9    private LocalDate hireDay;
10 
11    public Employee(String name, double salary, int year, int month, int day)
12    {
13       this.name = name;
14       this.salary = salary;
15       hireDay = LocalDate.of(year, month, day);
16    }
17 
18    public String getName()
19    {
20       return name;
21    }
22 
23    public double getSalary()
24    {
25       return salary;
26    }
27 
28    public LocalDate getHireDay()
29    {
30       return hireDay;
31    }
32 
33    public void raiseSalary(double byPercent)
34    {
35       double raise = salary * byPercent / 100;
36       salary += raise;
37    }
38 }

Manager类:

package inheritance;

import java.time.*;

public class Employee
{
   private String name;
   private double salary;
   private LocalDate hireDay;

   public Employee(String name, double salary, int year, int month, int day)
   {
      this.name = name;
      this.salary = salary;
      hireDay = LocalDate.of(year, month, day);
   }

   public String getName()
   {
      return name;
   }

   public double getSalary()
   {
      return salary;
   }

   public LocalDate getHireDay()
   {
      return hireDay;
   }

   public void raiseSalary(double byPercent)
   {
      double raise = salary * byPercent / 100;
      salary += raise;
   }
}

 

测试程序2:

Ÿ   编辑、编译、调试运行教材PersonTest程序(教材163页-165页);

Ÿ   掌握超类的定义及其使用要求;

Ÿ   掌握利用超类扩展子类的要求;

Ÿ   在程序中相关代码处添加新知识的注释。

PersonTest类:

package abstractClasses;

/**
 * This program demonstrates abstract classes.
 * @version 1.01 2004-02-21
 * @author Cay Horstmann
 */
public class PersonTest
{
   public static void main(String[] args)
   {
      Person[] people = new Person[2];

      // 用Student和Employee对象填充人员数组
      people[0] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
      people[1] = new Student("Maria Morris", "computer science");

      // 打印所有Person对象的名称和描述
      for (Person p : people)
         System.out.println(p.getName() + ", " + p.getDescription());
   }
}

Person类:

package abstractClasses;

public abstract class Person//定义抽象类型Person
{
   public abstract String getDescription();//定义抽象描述
   private String name;

   public Person(String name)
   {
      this.name = name;
   }

   public String getName()
   {
      return name;
   }
}

Employee类

package abstractClasses;

import java.time.*;

public class Employee extends Person//子类Employee继承父类Person
{
   private double salary;
   private LocalDate hireDay;

   public Employee(String name, double salary, int year, int month, int day)
   {
      super(name);//继承父类的方法
      this.salary = salary;
      hireDay = LocalDate.of(year, month, day);//hireDay使用LocalDate的方法
   }

   public double getSalary()
   {
      return salary;
   }

   public LocalDate getHireDay()
   {
      return hireDay;
   }

   public String getDescription()
   {
      return String.format("an employee with a salary of $%.2f", salary);
   }

   public void raiseSalary(double byPercent)
   {
      double raise = salary * byPercent / 100;
      salary += raise;
   }
}

Student:

package abstractClasses;

public class Student extends Person
//子类Student继承父类Person { private String major; /** * @param nama the student''s name * @param major the student''s major */ public Student(String name, String major) { // 将name传递给父类构造函数 super(name); this.major = major; } public String getDescription() { return "a student majoring in " + major; } }

 

测试程序3:

Ÿ   编辑、编译、调试运行教材程序5-8、5-9、5-10,结合程序运行结果理解程序(教材174页-177页);

Ÿ   掌握Object类的定义及用法;

Ÿ   在程序中相关代码处添加新知识的注释。

EqualsTest

package equals;

/**
 * This program demonstrates the equals method.
 * @version 1.12 2012-01-26
 * @author Cay Horstmann
 */
public class EqualsTest
{
   public static void main(String[] args)
   {
      Employee alice1 = new Employee("Alice Adams", 75000, 1987, 12, 15);
      Employee alice2 = alice1;
      Employee alice3 = new Employee("Alice Adams", 75000, 1987, 12, 15);
      Employee bob = new Employee("Bob Brandson", 50000, 1989, 10, 1);

      System.out.println("alice1 == alice2: " + (alice1 == alice2));

      System.out.println("alice1 == alice3: " + (alice1 == alice3));

      System.out.println("alice1.equals(alice3): " + alice1.equals(alice3));

      System.out.println("alice1.equals(bob): " + alice1.equals(bob));

      System.out.println("bob.toString(): " + bob);

      Manager carl = new Manager("Carl Cracker", 80000, 1987, 12, 15);
      Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15);
      boss.setBonus(5000);
      System.out.println("boss.toString(): " + boss);
      System.out.println("carl.equals(boss): " + carl.equals(boss));
      System.out.println("alice1.hashCode(): " + alice1.hashCode());
      System.out.println("alice3.hashCode(): " + alice3.hashCode());
      System.out.println("bob.hashCode(): " + bob.hashCode());
      System.out.println("carl.hashCode(): " + carl.hashCode());
   }
}

Employee:

package equals;

import java.time.*;
import java.util.Objects;

public class Employee
{
   private String name;
   private double salary;
   private LocalDate hireDay;

   public Employee(String name, double salary, int year, int month, int day)
   {
      this.name = name;
      this.salary = salary;
      hireDay = LocalDate.of(year, month, day);
   }

   public String getName()
   {
      return name;
   }

   public double getSalary()
   {
      return salary;
   }

   public LocalDate getHireDay()
   {
      return hireDay;
   }

   public void raiseSalary(double byPercent)
   {
      double raise = salary * byPercent / 100;
      salary += raise;
   }

   public boolean equals(Object otherObject)
   {
      // 快速测试,看看这些对象是否相同
      if (this == otherObject) return true;
      // 如果显式参数为空,则必须返回false
      if (otherObject == null) return false;
      // 如果类不匹配,它们就不能相等
      if (getClass() != otherObject.getClass()) return false;
      Employee other = (Employee) otherObject;
      // 测试字段是否具有相同的值
      return Objects.equals(name, other.name) && salary == other.salary && Objects.equals(hireDay, other.hireDay);
   }

   public int hashCode()
   {
      return Objects.hash(name, salary, hireDay); 
   }

   public String toString()
   {
      return getClass().getName() + "[name=" + name + ",salary=" + salary + ",hireDay=" + hireDay
            + "]";
   }
}

Manager:

package equals;

public class Manager extends Employee//子类Manager继承父类Employee
{
   private double bonus;

   public Manager(String name, double salary, int year, int month, int day)
   {
      super(name, salary, year, month, day);
      bonus = 0;
   }

   public double getSalary()
   {
      double baseSalary = super.getSalary();
      return baseSalary + bonus;
   }

   public void setBonus(double bonus)
   {
      this.bonus = bonus;
   }

   public boolean equals(Object otherObject)
   {
      if (!super.equals(otherObject)) return false;
      Manager other = (Manager) otherObject;
      // super.equals检查这个和其他属于同一个类
      return bonus == other.bonus;
   }

   public int hashCode()
   {
      return java.util.Objects.hash(super.hashCode(), bonus);
   }

   public String toString()
   {
      return super.toString() + "[bonus=" + bonus + "]";
   }
}

 

 

测试程序4:

Ÿ   在elipse IDE中调试运行程序5-11(教材182页),结合程序运行结果理解程序;

Ÿ   掌握ArrayList类的定义及用法;

Ÿ   在程序中相关代码处添加新知识的注释。

package arrayList;

import java.util.*;

/**
 * This program demonstrates the ArrayList class.
 * @version 1.11 2012-01-26
 * @author Cay Horstmann
 */
public class ArrayListTest
{
   public static void main(String[] args)
   {
      // 用三个Employee对象填充staff数组列表
      ArrayList<Employee> staff = new ArrayList<>();

      staff.add(new Employee("Carl Cracker", 75000, 1987, 12, 15));
      staff.add(new Employee("Harry Hacker", 50000, 1989, 10, 1));
      staff.add(new Employee("Tony Tester", 40000, 1990, 3, 15));
      for (Employee e : staff)
         e.raiseSalary(5);

      // 打印所有Employee对象的信息
      for (Employee e : staff)
         System.out.println("name=" + e.getName() + ",salary=" + e.getSalary() + ",hireDay="
               + e.getHireDay());
   }
}

Employee

package arrayList;

import java.time.*;

public class Employee
{
   private String name;
   private double salary;
   private LocalDate hireDay;

   public Employee(String name, double salary, int year, int month, int day)
   {
      this.name = name;
      this.salary = salary;
      hireDay = LocalDate.of(year, month, day);
   }

   public String getName()
   {
      return name;
   }

   public double getSalary()
   {
      return salary;
   }

   public LocalDate getHireDay()
   {
      return hireDay;
   }

   public void raiseSalary(double byPercent)
   {
      double raise = salary * byPercent / 100;
      salary += raise;
   }
}

 

 

测试程序5:

Ÿ   编辑、编译、调试运行程序5-12(教材189页),结合运行结果理解程序;

Ÿ   掌握枚举类的定义及用法;

Ÿ   在程序中相关代码处添加新知识的注释。

package enums;

import java.util.*;

/**
 * This program demonstrates enumerated types.
 * @version 1.0 2004-05-24
 * @author Cay Horstmann
 */
public class EnumTest
{  
   public static void main(String[] args)
   {  
      Scanner in = new Scanner(System.in);
      System.out.print("Enter a size: (SMALL, MEDIUM, LARGE, EXTRA_LARGE) ");
      String input = in.next().toUpperCase();
      Size size = Enum.valueOf(Size.class, input);
      System.out.println("size=" + size);
      System.out.println("abbreviation=" + size.getAbbreviation());
      if (size == Size.EXTRA_LARGE)//判断语句
         System.out.println("Good job--you paid attention to the _.");      
   }
}

enum Size
{
   SMALL("S"), MEDIUM("M"), LARGE("L"), EXTRA_LARGE("XL");

   private Size(String abbreviation) { this.abbreviation = abbreviation; }
   public String getAbbreviation() { return abbreviation; }

   private String abbreviation;
}

 

 

实验2编程练习1

Ÿ   定义抽象类Shape:

属性:不可变常量double PI,值为3.14;

方法:public double getPerimeter();public double getArea())。

Ÿ   让Rectangle与Circle继承自Shape类。

Ÿ   编写double sumAllArea方法输出形状数组中的面积和和double sumAllPerimeter方法输出形状数组中的周长和。

Ÿ   main方法中

1)输入整型值n,然后建立n个不同的形状。如果输入rect,则再输入长和宽。如果输入cir,则再输入半径。
2) 然后输出所有的形状的周长之和,面积之和。并将所有的形状信息以样例的格式输出。
3) 最后输出每个形状的类型与父类型,使用类似shape.getClass()(获得类型),shape.getClass().getSuperclass()(获得父类型);

思考sumAllArea和sumAllPerimeter方法放在哪个类中更合适?

输入样例:

3

rect

1 1

rect

2 2

cir

1

输出样例:

18.28

8.14

[Rectangle [width=1, length=1], Rectangle [width=2, length=2], Circle [radius=1]]

class Rectangle,class Shape

class Rectangle,class Shape

class Circle,class Shape

Test类:

 

package bbb;
import java.util.Scanner;
public class Test {
     public static void main(String[] args) {
      Scanner in = new Scanner(System.in);
      System.out.println("个数");
      int a = in.nextInt();
      System.out.println("种类");
      String rect="rect";
            String cir="cir";
      Shape[] num=new Shape[a];
      for(int i=0;i<a;i++){
       String input=in.next();
       if(input.equals(rect)) {
       System.out.println("长和宽");
       int length = in.nextInt();
       int width = in.nextInt();
             num[i]=new Rectangle(width,length);
             System.out.println("Rectangle["+"length:"+length+"  width:"+width+"]");
             }
       if(input.equals(cir)) {
             System.out.println("半径");
          int radius = in.nextInt();
          num[i]=new Circle(radius);
          System.out.println("Circle["+"radius:"+radius+"]");
             }
             }
             Test c=new Test();
             System.out.println("求和");
             System.out.println(c.sumAllPerimeter(num));
             System.out.println(c.sumAllArea(num));
             
             for(Shape s:num) {
                 System.out.println(s.getClass()+","+s.getClass().getSuperclass());
                 }
             }
     
               public double sumAllArea(Shape score[])
               {
               double sum=0;
               for(int i=0;i<score.length;i++)
                   sum+= score[i].getArea();
                   return sum;
               }
               public double sumAllPerimeter(Shape score[])
               {
               double sum=0;
               for(int i=0;i<score.length;i++)
                   sum+= score[i].getPerimeter();
                   return sum;
               }    
    }

 

shape类

package bbb;
    abstract class Shape { //定义抽象父类Shape
    abstract double getPerimeter(); //定义求解周长的方法
    abstract double getArea(); //定义求解面积的方法
    }

    class Rectangle extends Shape{ 
    private int length;
    private int width;
    public Rectangle(int length, int width) {
        this.length = length;
        this.width = width;
    }
    //继承父类
    double getPerimeter(){ //调用父类求周长的方法
    return 2*(length+width);
    }
    double getArea(){
    return length*width; //调用父类求面积的方法
    }
    }

    class Circle extends Shape{
    private int radius;
    public Circle(int radius) {
        this.radius = radius;
    }
    double getPerimeter(){
    return 2 * Math.PI * radius;
    }
    double getArea(){
    return Math.PI * radius * radius;
    }
    }

 

 

实验3编程练习2

编制一个程序,将身份证号.txt 中的信息读入到内存中,输入一个身份证号或姓名,查询显示查询对象的姓名、身份证号、年龄、性别和出生地。

package 实验6;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Scanner;

public class Demo3{
    private static ArrayList<Student> studentlist;
    public static void main(String[] args) {
        studentlist = new ArrayList<>();
        Scanner scanner = new Scanner(System.in);
        File file = new File("E:\\身份证号.txt");
        try {
            FileInputStream fis = new FileInputStream(file);
            BufferedReader in = new BufferedReader(new InputStreamReader(fis));
            String temp = null;
            while ((temp = in.readLine()) != null) {
                
                Scanner linescanner = new Scanner(temp);
                
                linescanner.useDelimiter(" ");    
                String name = linescanner.next();
                String number = linescanner.next();
                String sex = linescanner.next();
                String year = linescanner.next();
                String province =linescanner.nextLine();
                Student student = new Student();
                student.setName(name);
                student.setnumber(number);
                student.setsex(sex);
                student.setyear(year);
                student.setprovince(province);
                studentlist.add(student);

            }
        } catch (FileNotFoundException e) {
            System.out.println("学生信息文件找不到");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("学生信息文件读取错误");
            e.printStackTrace();
        }
        boolean isTrue = true;
        while (isTrue) {

            System.out.println("1.按姓名查询");
            System.out.println("2.按身份证号查询");
            System.out.println("3.退出");
            int nextInt = scanner.nextInt();
            switch (nextInt) {
            case 1:
                System.out.println("请输入姓名");
                String studentname = scanner.next();
                int nameint = findStudentByname(studentname);
                if (nameint != -1) {
                    System.out.println("查找信息为:身份证号:"
                            + studentlist.get(nameint).getnumber() + "    姓名:"
                            + studentlist.get(nameint).getName() +"    性别:"
                            +studentlist.get(nameint).getsex()   +"    年龄:"
                            +studentlist.get(nameint).getyaer()+"  地址:"
                            +studentlist.get(nameint).getprovince()
                            );
                } else {
                    System.out.println("不存在该学生");
                }
                break;
            case 2:
                System.out.println("请输入身份证号");
                String studentid = scanner.next();
                int idint = findStudentByid(studentid);
                if (idint != -1) {
                    System.out.println("查找信息为:身份证号:"
                            + studentlist.get(idint ).getnumber() + "    姓名:"
                            + studentlist.get(idint ).getName() +"    性别:"
                            +studentlist.get(idint ).getsex()   +"    年龄:"
                            +studentlist.get(idint ).getyaer()+"   地址:"
                            +studentlist.get(idint ).getprovince()
                            );
                } else {
                    System.out.println("不存在该学生");
                }
                break;
            case 3:
                isTrue = false;
                System.out.println("程序已退出!");
                break;
            default:
                System.out.println("输入有误");
            }
        }
    }

    public static int findStudentByname(String name) {
        int flag = -1;
        int a[];
        for (int i = 0; i < studentlist.size(); i++) {
            if (studentlist.get(i).getName().equals(name)) {
                flag= i;
            }
        }
        return flag;
    }

    public static int findStudentByid(String id) {
        int flag = -1;

        for (int i = 0; i < studentlist.size(); i++) {
            if (studentlist.get(i).getnumber().equals(id)) {
                flag = i;
            }
        }
        return flag;
    }   
}
package 实验6;    
    public class Student {

    private String name;
    private String number ;
    private String sex ;
    private String year;
    private String province;
   
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getnumber() {
        return number;
    }
    public void setnumber(String number) {
        this.number = number;
    }
    public String getsex() {
        return sex ;
    }
    public void setsex(String sex ) {
        this.sex =sex ;
    }
    public String getyaer() {
        return year;
    }
    public void setyear(String year ) {
        this.year=year ;
    }
    public String getprovince() {
    return province;
    }
    public void setprovince(String province) {
        this.province=province ;
    }
}

 

实验总结:

 理解继承的定义; 掌握了子类的定义要求 、多态性的概念及用法; 掌握了抽象类的定义及用途、Object类的用途及常用API、ArrayList类的定义方法及用法、枚举类定义方法及用途。并且在同学的帮助下成功完成了两个实验练习题,我相信我会慢慢的不再需要别人的帮助,独立的做出一些练习题。

 

201771010106 东文财《面向对象程序设计(java)》 实验 6

201771010106 东文财《面向对象程序设计(java)》 实验 6

实验六继承定义与使用

实验时间 2018-9-28

一。知识总结

1、继承的概述:在多个类中存在相同的属性和行为,把这些相同的部分抽取到一个单独的类中,把这个单独的类叫作父类,也叫基类或者超类,把其他被抽取的类叫作子类,并且父类的所有属性和方法(除 private 修饰的私有属性和方法外),子类都可以调用。这样的一种行为就叫做继承。(相同的东西在父类,不同的东西在子类)

2、继承的关键字:extends

3、继承的格式:class 子类名  extends  父类名 {   }

4、在代码中使用继承提高了代码的复用性和维护性,让类与类直接产生了关系。

5、继承的注意点:

①子类只能继承父类所有的非私有的成员方法和成员变量,private 修饰的不能继承。

②子类不能继承父类的构造方法,但可以通过   super   关键字去访问父类的构造方法。(先初始化父类,再执行自己)

③不同包不能继承。

 6、在使用  super  的时候,我们还需要了解关键字 super  和  this  的区别:

         super :到父类中去找方法,没有引用的作用;也可以用于其他方法中;与 this 调用构造方的重载一样,用于第一行。

         this:是指当前正在初始化的这个对象的引用。

二。实验部分:

1、实验目的与要求

(1) 理解继承的定义;

(2) 掌握子类的定义要求

(3) 掌握多态性的概念及用法;

(4) 掌握抽象类的定义及用途;

(5) 掌握类中 4 个成员访问权限修饰符的用途;

(6) 掌握抽象类的定义方法及用途;

(7) 掌握 Object 类的用途及常用 API;

(8) 掌握 ArrayList 类的定义方法及用法;

(9) 掌握枚举类定义方法及用途。

2、实验内容和步骤

实验 1: 导入第 5 章示例程序,测试并进行代码注释。

测试程序 1:

Ÿ   在 elipse IDE 中编辑、调试、运行程序 5-1 (教材 152 页 - 153 页) ;

Ÿ   掌握子类的定义及用法;

Ÿ   结合程序运行结果,理解并总结 OO 风格程序构造特点,理解 Employee 和 Manager 类的关系子类的用途,并在代码中添加注释。

package inheritance;

import java.time.*;

public class Employee
{
   private String name;
   private double salary;
   private LocalDate hireDay;
   //构建三个私有对象
   public Employee(String name, double salary, int year, int month, int day)
   {
      this.name = name;
      this.salary = salary;
      hireDay = LocalDate.of(year, month, day);
   }

   public String getName()
   {
      return name;
   }

   public double getSalary()
   {
      return salary;
   }

   public LocalDate getHireDay()
   {
      return hireDay;
   }

   public void raiseSalary(double byPercent)
   {
      double raise = salary * byPercent / 100;
      salary += raise;
   }
}

 

package inheritance;

public class Manager extends Employee
//关键字extends表示继承。表明正在构造一个新类派生于一个已经存在的类。已经存在的类称为超类/基类/或者父类;新类称为子类/派生类/或者孩子类。 {
private double bonus; /** * @param name the employee''s name * @param salary the salary * @param year the hire year * @param month the hire month * @param day the hire day */ public Manager(String name, double salary, int year, int month, int day) { super(name, salary, year, month, day);
//调用超类中含有n,s,year,month,day参数的构造器 bonus
= 0; } public double getSalary()
//子类要想访问要想访问超类中的方法需要使用特定的关键字super, {
double baseSalary = super.getSalary(); return baseSalary + bonus; } public void setBonus(double b) { bonus = b; } }

 

package inheritance;

/**
 * This program demonstrates inheritance.
 * @version 1.21 2004-02-21
 * @author Cay Horstmann
 */
public class ManagerTest
{
   public static void main(String[] args)
   {
      // 构建管理者对象
      Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15);
      boss.setBonus(5000);

      Employee[] staff = new Employee[3];

      //  用管理者和雇员对象填充工作人员数组

      staff[0] = boss;
      staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
      staff[2] = new Employee("Tommy Tester", 40000, 1990, 3, 15);

      // 打印所有员工对象的信息
      for (Employee e : staff)
         System.out.println("name=" + e.getName() + ",salary=" + e.getSalary());
   }
}

实验结果:

测试程序 2:

Ÿ   编辑、编译、调试运行教材 PersonTest 程序(教材 163 页 - 165 页);

Ÿ   掌握超类的定义及其使用要求;

Ÿ   掌握利用超类扩展子类的要求;

Ÿ   在程序中相关代码处添加新知识的注释。

package abstractClasses;

import java.time.*;

public class Employee extends Person
{
   private double salary;
   private LocalDate hireDay;

   public Employee(String name, double salary, int year, int month, int day)
   {
      super(name);
      this.salary = salary;
      hireDay = LocalDate.of(year, month, day);
   }

   public double getSalary()
   {
      return salary;
   }

   public LocalDate getHireDay()
   {
      return hireDay;
   }
    //重写父类方法,返回一个格式化的字符串
   public String getDescription()
   {
      return String.format("an employee with a salary of $%.2f", salary);
   }

   public void raiseSalary(double byPercent)
   {
      double raise = salary * byPercent / 100;
      salary += raise;
   }
}

 

package abstractClasses;

public abstract class Person
{
//包含一个或多个抽象方法的类被称为抽象类,由abstract关键字修饰
public abstract String getDescription(); private String name; public Person(String name) { this.name = name; } public String getName() { return name; } }

 

package abstractClasses;

/**
 * This program demonstrates abstract classes.
 * @version 1.01 2004-02-21
 * @author Cay Horstmann
 */
public class PersonTest
{
   public static void main(String[] args)
   {
//抽象类的声明,但不能将抽象类实例化 ,实例化的是Person类的子类 Person[] people
= new Person[2]; // 用学生和雇员填充人物数组

people[0] = new Employee("Harry Hacker", 50000, 1989, 10, 1); people[1] = new Student("Maria Morris", "computer science"); // 打印所有人对象的名称和描述 for (Person p : people) System.out.println(p.getName() + ", " + p.getDescription()); } }

 

package abstractClasses;

public class Student extends Person
{
   private String major;

   /**
    * @param nama the student''s name
    * @param major the student''s major
    */
   public Student(String name, String major)
   {
      // 通过n to 总纲构造函数
      super(name);
      this.major = major;
   }

   public String getDescription()
   {
      return "a student majoring in " + major;
   }
}

实验结果:

测试程序 3:

Ÿ   编辑、编译、调试运行教材程序 5-8、5-9、5-10,结合程序运行结果理解程序(教材 174 页 - 177 页);

Ÿ   掌握 Object 类的定义及用法;

Ÿ   在程序中相关代码处添加新知识的注释。

package equals;

import java.time.*;
import java.util.Objects;

public class Employee
{
   private String name;
   private double salary;
   private LocalDate hireDay;

   public Employee(String name, double salary, int year, int month, int day)
   {
      this.name = name;
      this.salary = salary;
      hireDay = LocalDate.of(year, month, day);
   }

   public String getName()
   {
      return name;
   }

   public double getSalary()
   {
      return salary;
   }

   public LocalDate getHireDay()
   {
      return hireDay;
   }

   public void raiseSalary(double byPercent)
   {
      double raise = salary * byPercent / 100;
      salary += raise;
   }

   public boolean equals(Object otherObject)
   {
      //这里获得一个对象参数,第一个if语句判断两个引用是否是同一个,如果是那么这两个对象肯定相等
      if (this == otherObject) return true;

      //  如果显式参数为空,则必须返回false
      if (otherObject == null) return false;

      // if the classes don''t match, they can''t be equal
      if (getClass() != otherObject.getClass()) return false;

      // 现在我们知道另一个对象是非空雇员
      Employee other = (Employee) otherObject;

      // test whether the fields have identical values
      return Objects.equals(name, other.name) && salary == other.salary && Objects.equals(hireDay, other.hireDay);
   }

   public int hashCode()
   {
      return Objects.hash(name, salary, hireDay); 
   }

   public String toString()// toString()方法
   {
      return getClass().getName() + "[name=" + name + ",salary=" + salary + ",hireDay=" + hireDay
            + "]";
   }
}

 

package equals;

/**
 * This program demonstrates the equals method.
 * @version 1.12 2012-01-26
 * @author Cay Horstmann
 */
public class EqualsTest
{
   public static void main(String[] args)
   {
      Employee alice1 = new Employee("Alice Adams", 75000, 1987, 12, 15);
      Employee alice2 = alice1;
      Employee alice3 = new Employee("Alice Adams", 75000, 1987, 12, 15);
      Employee bob = new Employee("Bob Brandson", 50000, 1989, 10, 1);

      System.out.println("alice1 == alice2: " + (alice1 == alice2));

      System.out.println("alice1 == alice3: " + (alice1 == alice3));

      System.out.println("alice1.equals(alice3): " + alice1.equals(alice3));

      System.out.println("alice1.equals(bob): " + alice1.equals(bob));

      System.out.println("bob.toString(): " + bob);

      Manager carl = new Manager("Carl Cracker", 80000, 1987, 12, 15);
      Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15);
      boss.setBonus(5000);
      System.out.println("boss.toString(): " + boss);
      System.out.println("carl.equals(boss): " + carl.equals(boss));
      System.out.println("alice1.hashCode(): " + alice1.hashCode());
      System.out.println("alice3.hashCode(): " + alice3.hashCode());
      System.out.println("bob.hashCode(): " + bob.hashCode());
      System.out.println("carl.hashCode(): " + carl.hashCode());
   }
}

 

package equals;

public class Manager extends Employee
{
   private double bonus;

   public Manager(String name, double salary, int year, int month, int day)
   {
      super(name, salary, year, month, day);
      bonus = 0;
   }

   public double getSalary()
   {
      double baseSalary = super.getSalary();
      return baseSalary + bonus;
   }

   public void setBonus(double bonus)
   {
      this.bonus = bonus;
   }

   public boolean equals(Object otherObject)
   {
      if (!super.equals(otherObject)) return false;
      Manager other = (Manager) otherObject;
      // 检查这个和其他属于同一个类
      return bonus == other.bonus;
   }

   public int hashCode()
   {
      return java.util.Objects.hash(super.hashCode(), bonus);
   }

   public String toString()
   {
      return super.toString() + "[bonus=" + bonus + "]";
   }
}

实验结果:

测试程序 4:

Ÿ   在 elipse IDE 中调试运行程序 5-11(教材 182 页),结合程序运行结果理解程序;

Ÿ   掌握 ArrayList 类的定义及用法;

Ÿ   在程序中相关代码处添加新知识的注释。

package arrayList;

import java.util.*;

/**
 * This program demonstrates the ArrayList class.
 * @version 1.11 2012-01-26
 * @author Cay Horstmann
 */
public class ArrayListTest
{
   public static void main(String[] args)
   {
      // 用三个雇员对象填充工作人员数组列表    
ArrayList<Employee> staff = new ArrayList<>(); staff.add(new Employee("Carl Cracker", 75000, 1987, 12, 15)); staff.add(new Employee("Harry Hacker", 50000, 1989, 10, 1)); staff.add(new Employee("Tony Tester", 40000, 1990, 3, 15)); //把每个人的薪水提高5% for (Employee e : staff) e.raiseSalary(5); // 打印所有员工对象的信息 for (Employee e : staff) System.out.println("name=" + e.getName() + ",salary=" + e.getSalary() + ",hireDay=" + e.getHireDay()); } }

 

package arrayList;

import java.time.*;

public class Employee
{
   private String name;
   private double salary;
   private LocalDate hireDay;

   public Employee(String name, double salary, int year, int month, int day)
   {
      this.name = name;
      this.salary = salary;
      hireDay = LocalDate.of(year, month, day);
   }

   public String getName()
   {
      return name;
   }

   public double getSalary()
   {
      return salary;
   }

   public LocalDate getHireDay()
   {
      return hireDay;
   }

   public void raiseSalary(double byPercent)
   {
      double raise = salary * byPercent / 100;
      salary += raise;
   }
}

 

 

实验结果:

测试程序 5:

Ÿ   编辑、编译、调试运行程序 5-12(教材 189 页),结合运行结果理解程序;

Ÿ   掌握枚举类的定义及用法;

Ÿ   在程序中相关代码处添加新知识的注释。

package enums;

import java.util.*;

/**
 * This program demonstrates enumerated types.
 * @version 1.0 2004-05-24
 * @author Cay Horstmann
 */
public class EnumTest
{  
   private static Scanner in;

public static void main(String[] args)
   {  
      in = new Scanner(System.in);
      System.out.print("Enter a size: (SMALL, MEDIUM, LARGE, EXTRA_LARGE) ");
      String input = in.next().toUpperCase();
      Size size = Enum.valueOf(Size.class, input);
      System.out.println("size=" + size);
      System.out.println("abbreviation=" + size.getAbbreviation());
      if (size == Size.EXTRA_LARGE)
         System.out.println("Good job--you paid attention to the _.");      
   }
}

enum Size
{
   SMALL("S"), MEDIUM("M"), LARGE("L"), EXTRA_LARGE("XL");

   private Size(String abbreviation) { this.abbreviation = abbreviation; }
   public String getAbbreviation() { return abbreviation; }

   private String abbreviation;
}

实验结果:

实验 2编程练习 1

Ÿ   定义抽象类 Shape:

属性:不可变常量 double PI,值为 3.14;

方法:public double getPerimeter ();public double getArea ())。

Ÿ   让 Rectangle 与 Circle 继承自 Shape 类。

Ÿ   编写 double sumAllArea 方法输出形状数组中的面积和和 double sumAllPerimeter 方法输出形状数组中的周长和。

Ÿ   main 方法中

1)输入整型值 n,然后建立 n 个不同的形状。如果输入 rect,则再输入长和宽。如果输入 cir,则再输入半径。
2) 然后输出所有的形状的周长之和,面积之和。并将所有的形状信息以样例的格式输出。
3) 最后输出每个形状的类型与父类型,使用类似 shape.getClass ()(获得类型),shape.getClass ().getSuperclass ()(获得父类型);

思考 sumAllArea 和 sumAllPerimeter 方法放在哪个类中更合适?

输入样例:

3

rect

1 1

rect

2 2

cir

1

输出样例:

18.28

8.14

[Rectangle [width=1, length=1], Rectangle [width=2, length=2], Circle [radius=1]]

class Rectangle,class Shape

class Rectangle,class Shape

class Circle,class Shape

package shape;

    import java.math.*;
    import java.util.*;
    import shape.shape;
    import shape.Rectangle;
    import shape.Circle;

    public class shapecount 
    {

        public static void main(String[] args) 
        {
            Scanner in = new Scanner(System.in);
            String rect = "rect";
            String cir = "cir";
            System.out.print("请输入形状个数:");
            int n = in.nextInt();
            shape[] score = new shape[n];
            for(int i=0;i<n;i++)
            {
                System.out.println("请输入形状类型 (rect or cir):");
                String input = in.next();
                if(input.equals(rect))
                {
                    double length = in.nextDouble();
                    double width = in.nextDouble();
                    System.out.println("Rectangle["+"length:"+length+"  width:"+width+"]");
                    score[i] = new Rectangle(width,length);
                }
                if(input.equals(cir)) 
                {
                    double radius = in.nextDouble();
                    System.out.println("Circle["+"radius:"+radius+"]");
                    score[i] = new Circle(radius);
                }
            }
            shapecount c = new shapecount();
            System.out.println(c.sumAllPerimeter(score));
            System.out.println(c.sumAllArea(score));
            for(shape s:score) 
            {

                System.out.println(s.getClass()+",  "+s.getClass().getSuperclass());
            }
        }

        public double sumAllArea(shape score[])
        {
             double sum = 0;
             for(int i = 0;i<score.length;i++)
                 sum+= score[i].getArea();
             return sum;
        }
        
        public double sumAllPerimeter(shape score[])
        {
             double sum = 0;
             for(int i = 0;i<score.length;i++)
                 sum+= score[i].getPerimeter();
             return sum;
        }
        
    }

 

package shape;

    public class Rectangle extends shape
    {
        private double width;
        private double length;
        public Rectangle(double w,double l)
        {
            this.width = w;
            this.length = l;
        }
        public double getPerimeter()
        {
            double Perimeter = (width+length)*2;
            return Perimeter;
        }
        public double getArea()
        {
            double Area = width*length;
            return Area;
        }

          public String toString()
          {
              return getClass().getName() + "[ width=" +  width + "]"+ "[length=" + length + "]";
          }
    }

 

package shape;

    public abstract class shape
    {
        double PI = 3.14;
        public abstract double  getPerimeter();
        public abstract double  getArea();
    }

 

package shape;

    public class Circle extends shape
    {

        private double radius;
        public Circle(double r)
        {
            radius = r;
        }
        public double getPerimeter()
        {
            double Perimeter = 2*PI*radius;
            return Perimeter;
        }
        public double getArea()
        {
            double Area = PI*radius*radius;
            return Area;
        }
        public String toString()
          {
              return  getClass().getName() + "[radius=" + radius + "]";
       }  
    }

实验结果:

 

实验 3编程练习 2

编制一个程序,将身份证号.txt 中的信息读入到内存中,输入一个身份证号或姓名,查询显示查询对象的姓名、身份证号、年龄、性别和出生地。

 

package qq;


    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    import java.util.Scanner;

    public class Test{
        private static ArrayList<Citizen> citizenlist;
        public static void main(String[] args) {
            citizenlist = new ArrayList<>();
            Scanner scanner = new Scanner(System.in);
            File file = new File("D:\\身份证号.txt");
            try {
                FileInputStream fis = new FileInputStream(file);
                BufferedReader in = new BufferedReader(new InputStreamReader(fis));
                String temp = null;
                while ((temp = in.readLine()) != null) {
                    
                    Scanner linescanner = new Scanner(temp);
                    
                    linescanner.useDelimiter(" ");    
                    String name = linescanner.next();
                    String id = linescanner.next();
                    String sex = linescanner.next();
                    String age = linescanner.next();
                    String address =linescanner.nextLine();
                    Citizen citizen = new Citizen();
                    citizen.setName(name);
                    citizen.setId(id);
                    citizen.setSex(sex);
                    citizen.setAge(age);
                    citizen.setAddress(address);
                    citizenlist.add(citizen);

                }
            } catch (FileNotFoundException e) {
                System.out.println("信息文件找不到");
                e.printStackTrace();
            } catch (IOException e) {
                System.out.println("信息文件读取错误");
                e.printStackTrace();
            }
            boolean isTrue = true;
            while (isTrue) {

                System.out.println("1.按姓名查询");
                System.out.println("2.按身份证号查询");
                System.out.println("3.退出");
                int nextInt = scanner.nextInt();
                switch (nextInt) {
                case 1:
                    System.out.println("请输入姓名");
                    String citizenname = scanner.next();
                    int nameint = findCitizenByname(citizenname);
                    if (nameint != -1) {
                        System.out.println("查找信息为:身份证号:"
                                + citizenlist.get(nameint).getId() + "    姓名:"
                                + citizenlist.get(nameint).getName() +"    性别:"
                                +citizenlist.get(nameint).getSex()   +"    年龄:"
                                +citizenlist.get(nameint).getAge()+"  地址:"
                                +citizenlist.get(nameint).getAddress()
                                );
                    } else {
                        System.out.println("不存在该公民");
                    }
                    break;
                case 2:
                    System.out.println("请输入身份证号");
                    String citizenid = scanner.next();
                    int idint = findCitizenByid(citizenid);
                    if (idint != -1) {
                        System.out.println("查找信息为:身份证号:"
                                + citizenlist.get(idint ).getId() + "    姓名:"
                                + citizenlist.get(idint ).getName() +"    性别:"
                                +citizenlist.get(idint ).getSex()   +"    年龄:"
                                +citizenlist.get(idint ).getAge()+"   地址:"
                                +citizenlist.get(idint ).getAddress()
                                );
                    } else {
                        System.out.println("不存在该公民");
                    }
                    break;
                case 3:
                    isTrue = false;
                    System.out.println("程序已退出!");
                    break;
                default:
                    System.out.println("输入有误");
                }
            }
        }

        public static int findCitizenByname(String name) {
            int flag = -1;
            int a[];
            for (int i = 0; i < citizenlist.size(); i++) {
                if (citizenlist.get(i).getName().equals(name)) {
                    flag= i;
                }
            }
            return flag;
        }

        public static int findCitizenByid(String id) {
            int flag = -1;

            for (int i = 0; i < citizenlist.size(); i++) {
                if (citizenlist.get(i).getId().equals(id)) {
                    flag = i;
                }
            }
            return flag;
        }   
    }

 

package qq;


    public class Citizen {

        private String name;
        private String id ;
        private String sex ;
        private String age;
        private String address;
       
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getId() {
            return id;
        }
        public void setId(String id) {
            this.id = id;
        }
        public String getSex() {
            return sex ;
        }
        public void setSex(String sex ) {
            this.sex =sex ;
        }
        public String getAge() {
            return age;
        }
        public void setAge(String age ) {
            this.age=age ;
        }
        public String getAddress() {
            return address;
        }
        public void setAddress(String address) {
            this.address=address ;
        }
    }

实验结果:

实验总结:

     上周我们学习了第五章,这章中主要学了继承这一概念,通过继承人们可以在已存在的类构造一个新类,继承已存在的类就是复用这些类的方法和域,通过继承这一概念我们学习了一些类的概念如:超类,基类(父类),子类等。总的来说本章的知识点也是比较重要的,不过我对本章的知识掌握的不是很好,我会继续努力的,多多敲代码。

201771010106 东文财《面向对象程序设计(java)》 实验 8

201771010106 东文财《面向对象程序设计(java)》 实验 8

实验六 接口的定义与使用

实验时间 2018-10-18

一、理论知识部分

抽象类:

       用 abstract 来声明,没有具体实例对象的类,不能用 new 来创建对象。可包含常规类所包含的任何东西。抽象类必须由子类继承,如果 abstract 类的子类不是抽象类,那么子类必须重写父类中所有的 abstract 方法。

接口:

       用 interface 声明,是抽象方法和常量值定义的集合。从本质上讲,接口是一种特殊的抽象类,这种抽象类中只包含常量和方法的定义,而没有变量和方法的定义。接口中只能定义抽象方法,而且这些方法默认为是 public 的。只要类实现了接口,就可以在任何需要该接 口的地方使用这个类的对象。此外,一个类可以实现多个接口。

接口与抽象类的区别:

(1)接口不能实现任何方法,而抽象类可以。

(2)类可以实现许多接口,但只有一个父类。

(3)接口不是类分级结构的一部分,无任何联系的类可以实现相同的接口。

回调 (callback):

       一种程序设计模式,在这种模式中,可指出某个特定事件发生时程序应该采取的动作。当拷贝一个对象变量时,原始变量与拷贝变量引用同一个对象。这样,改变一个变量所引用 的对象会对另一个变量产生影响。如果要创建一个对象新的 copy,它的最初状态与 original 一样,但以后可以各自改变状态,就需要使用 Object 类的 clone 方法。Object 类的 clone () 方法是一个 native 方法。Object 类中的 clone () 方法被 protected 修饰符修饰。这意味着在用户编写的代码中不能直接调用它。如果要直接应用 clone () 方法,就需覆盖 clone () 方法,并要把 clone () 方法的属性设置为 public。  Object.clone () 方法返回一个 Object 对象。必须进行强制类型转换才能得到需要的类型。

浅层拷贝:

        被拷贝对象的所有常量成员和基本类型属性都有与原来对象相同的拷贝值,而若成员域是一个对象,则被拷贝对象该对象域的对象引用仍然指向原来的对象。

深层拷贝:

       被拷贝对象的所有成员域都含有与原来对象相同的值,且对象域将指向被复制过的新对象,而不是原有对象被引用的对象。换言之, 深层拷贝将拷贝对象内引用的对象也拷贝一遍 。

Java 中对象克隆的实现:

       在子类中实现 Cloneable 接口。为了获取对象的一份拷贝,可以利用 Object 类的 clone 方法。在子类中覆盖超类的 clone 方法,声明为 public。在子类的 clone 方法中,调用 super.clone ()。

二、实验部分

1、实验目的与要求

(1) 掌握接口定义方法;

(2) 掌握实现接口类的定义要求;

(3) 掌握实现了接口类的使用要求;

(4) 掌握程序回调设计模式;

(5) 掌握 Comparator 接口用法;

(6) 掌握对象浅层拷贝与深层拷贝方法;

(7) 掌握 Lambda 表达式语法;

(8) 了解内部类的用途及语法要求。

2、实验内容和步骤

实验 1 导入第 6 章示例程序,测试程序并进行代码注释。

测试程序 1:

l 编辑、编译、调试运行阅读教材 214 页 - 215 页程序 6-1、6-2,理解程序并分析程序运行结果;

l 在程序中相关代码处添加新知识的注释。

l 掌握接口的实现用法;

l 掌握内置接口 Compareable 的用法。

package interfaces;

public class Employee implements Comparable<Employee>
{
   private String name;
   private double salary;

   public Employee(String name, double salary)
   {
      this.name = name;
      this.salary = salary;
   }

   public String getName()
   {
      return name;
   }

   public double getSalary()
   {
      return salary;
   }

   public void raiseSalary(double byPercent)
   {
      double raise = salary * byPercent / 100;
      salary += raise;
   }

   /**
    * Compares employees by salary
    * @param other another Employee object
    * @return a negative value if this employee has a lower salary than
    * otherObject, 0 if the salaries are the same, a positive value otherwise
    */
   public int compareTo(Employee other)
   {
      return Double.compare(salary, other.salary);
   }
}

 

package interfaces;

import java.util.*;

/**
 * This program demonstrates the use of the Comparable interface.
 * @version 1.30 2004-02-27
 * @author Cay Horstmann
 */
public class EmployeeSortTest
{
   public static void main(String[] args)
   {
      Employee[] staff = new Employee[3];

      staff[0] = new Employee("Harry Hacker", 35000);
      staff[1] = new Employee("Carl Cracker", 75000);
      staff[2] = new Employee("Tony Tester", 38000);

      Arrays.sort(staff);

      // print out information about all Employee objects
      for (Employee e : staff)
         System.out.println("name=" + e.getName() + ",salary=" + e.getSalary());
   }
}

实验结果:

测试程序 2:

编辑、编译、调试以下程序,结合程序运行结果理解程序;

interface  A

{

  double g=9.8;

  void show( );

}

class C implements A

{

  public void show( )

  {System.out.println("g="+g);}

}

 

class InterfaceTest

{

  public static void main(String[ ] args)

  {

       A a=new C( );

       a.show( );

       System.out.println("g="+C.g);

  }

}

package gh;

public class yy {


        // TODO Auto-generated method stub
        interface  A
        {
          double g=9.8;
          void show( );
        }
        class C implements A
        {
          public void show( )
          {System.out.println("g="+g);}

        }

        class InterfaceTest

        {
          public static void main(String[ ] args)

          {
               A a=new C( );
               a.show( );

               System.out.println("g="+C.g);
          }

        }
    }

实验结果:

测试程序 3:

l 在 elipse IDE 中调试运行教材 223 页 6-3,结合程序运行结果理解程序;

l 26 行、36 行代码参阅 224 页,详细内容涉及教材 12 章。

l 在程序中相关代码处添加新知识的注释。

l 掌握回调程序设计模式;

package timer;

/**
   @version 1.01 2015-05-12
   @author Cay Horstmann
*/

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer; 
// to resolve conflict with java.util.Timer

public class TimerTest
{  
   public static void main(String[] args)
   {  
      ActionListener listener = new TimePrinter();

      // construct a timer that calls the listener
      // once every 10 seconds
      Timer t = new Timer(10000, listener);
      t.start();

      JOptionPane.showMessageDialog(null, "Quit program?");
      System.exit(0);
   }
}

class TimePrinter implements ActionListener
{  
   public void actionPerformed(ActionEvent event)
   {  
      System.out.println("At the tone, the time is " + new Date());
      Toolkit.getDefaultToolkit().beep();
   }
}

测试程序 4:

l 调试运行教材 229 页 - 231 页程序 6-4、6-5,结合程序运行结果理解程序;

l 在程序中相关代码处添加新知识的注释。

l 掌握对象克隆实现技术;

l 掌握浅拷贝和深拷贝的差别。

package clone;

/**
 * This program demonstrates cloning.
 * @version 1.10 2002-07-01
 * @author Cay Horstmann
 */
public class CloneTest
{
   public static void main(String[] args)
   {
      try
      {
         Employee original = new Employee("John Q. Public", 50000);
         original.setHireDay(2000, 1, 1);
         Employee copy = original.clone();
         copy.raiseSalary(10);
         copy.setHireDay(2002, 12, 31);
         System.out.println("original=" + original);
         System.out.println("copy=" + copy);
      }
      catch (CloneNotSupportedException e)
      {
         e.printStackTrace();
      }
   }
}

 

package clone;

import java.util.Date;
import java.util.GregorianCalendar;

public class Employee implements Cloneable
{
   private String name;
   private double salary;
   private Date hireDay;

   public Employee(String name, double salary)
   {
      this.name = name;
      this.salary = salary;
      hireDay = new Date();
   }

   public Employee clone() throws CloneNotSupportedException
   {
      // call Object.clone()
      Employee cloned = (Employee) super.clone();

      // clone mutable fields
      cloned.hireDay = (Date) hireDay.clone();

      return cloned;
   }

   /**
    * Set the hire day to a given date. 
    * @param year the year of the hire day
    * @param month the month of the hire day
    * @param day the day of the hire day
    */
   public void setHireDay(int year, int month, int day)
   {
      Date newHireDay = new GregorianCalendar(year, month - 1, day).getTime();
      
      // Example of instance field mutation
      hireDay.setTime(newHireDay.getTime());
   }

   public void raiseSalary(double byPercent)
   {
      double raise = salary * byPercent / 100;
      salary += raise;
   }

   public String toString()
   {
      return "Employee[name=" + name + ",salary=" + salary + ",hireDay=" + hireDay + "]";
   }
}

实验结果:

实验 2 导入第 6 章示例程序 6-6,学习 Lambda 表达式用法。

l 调试运行教材 233 页 - 234 页程序 6-6,结合程序运行结果理解程序;

l 在程序中相关代码处添加新知识的注释。

l 将 27-29 行代码与教材 223 页程序对比,将 27-29 行代码与此程序对比,体会 Lambda 表达式的优点。

 

package lambda;

import java.util.*;

import javax.swing.*;
import javax.swing.Timer;

/**
 * This program demonstrates the use of lambda expressions.
 * @version 1.0 2015-05-12
 * @author Cay Horstmann
 */
public class LambdaTest
{
   public static void main(String[] args)
   {
      String[] planets = new String[] { "Mercury", "Venus", "Earth", "Mars", 
            "Jupiter", "Saturn", "Uranus", "Neptune" };
      System.out.println(Arrays.toString(planets));
      System.out.println("Sorted in dictionary order:");
      Arrays.sort(planets);
      System.out.println(Arrays.toString(planets));
      System.out.println("Sorted by length:");
      Arrays.sort(planets, (first, second) -> first.length() - second.length());
      System.out.println(Arrays.toString(planets));
            
      Timer t = new Timer(1000, event ->
         System.out.println("The time is " + new Date()));
      t.start();   
         
      // keep program running until user selects "Ok"
      JOptionPane.showMessageDialog(null, "Quit program?");
      System.exit(0);         
   }
}

 实验结果:

注:以下实验课后完成

实验 3: 编程练习

编制一个程序,将身份证号.txt 中的信息读入到内存中;

l 按姓名字典序输出人员信息;

l 查询最大年龄的人员信息;

l 查询最小年龄人员信息;

输入你的年龄,查询身份证号.txt 中年龄与你最近人的姓名、身份证号、年龄、性别和出生地;

l 查询人员中是否有你的同乡。

package yu;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;

public class yy{
    private static ArrayList<People> Peoplelist;
    public static void main(String[] args) {
         Peoplelist = new ArrayList<>();
        Scanner scanner = new Scanner(System.in);
        File file = new File("D:\\java\\1\\身份证号.txt");
        try {
            FileInputStream fis = new FileInputStream(file);
            BufferedReader in = new BufferedReader(new InputStreamReader(fis));
            String temp = null;
            while ((temp = in.readLine()) != null) {
                
                Scanner linescanner = new Scanner(temp);
                
                linescanner.useDelimiter(" ");    
                String name = linescanner.next();
                String ID = linescanner.next();
                String sex = linescanner.next();
                String age = linescanner.next();
                String place =linescanner.nextLine();
                People People = new people();
                People.setname(name);
                People.setID(ID);
                People.setsex(sex);
                int a = Integer.parseInt(age);
                People.setage(a);
                People.setbirthplace(place);
                Peoplelist.add(People);

            }
        } catch (FileNotFoundException e) {
            System.out.println("查找不到信息");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("信息读取有误");
            e.printStackTrace();
        }
        boolean isTrue = true;
        while (isTrue) {
            System.out.println("————————————————————————————————————————");
            System.out.println("1:按姓名字典序输出人员信息");
            System.out.println("2:查询最大年龄人员信息和最小年龄人员信息");
            System.out.println("3:输入你的年龄,查询年龄与你最近人的所有信息");
            System.out.println("4:查询人员中是否有你的同乡");
           
            
            int nextInt = scanner.nextInt();
            switch (nextInt) {
            case 1:
                Collections.sort( Peoplelist);
                System.out.println( Peoplelist.toString());
                break;
            case 2:
                
                int max=0,min=100;int j,k1 = 0,k2=0;
                for(int i=1;i< Peoplelist.size();i++)
                {
                    j= Peoplelist.get(i).getage();
                   if(j>max)
                   {
                       max=j; 
                       k1=i;
                   }
                   if(j<min)
                   {
                       min=j; 
                       k2=i;
                   }

                }  
                System.out.println("年龄最大:"+ Peoplelist.get(k1));
                System.out.println("年龄最小:"+ Peoplelist.get(k2));
                break;
            case 3:
                System.out.println("place?");
                String find = scanner.next();        
                String place=find.substring(0,3);
                String place2=find.substring(0,3);
                for (int i = 0; i < Peoplelist.size(); i++) 
                {
                    if( Peoplelist.get(i).getbirthplace().substring(1,4).equals(place)) 
                        System.out.println(Peoplelist.get(i));

                } 

                break;
            case 4:
                System.out.println("年龄:");
                int yourage = scanner.nextInt();
                int near=agenear(yourage);
                int d_value=yourage-Peoplelist.get(near).getage();
                System.out.println(""+Peoplelist.get(near));
           /*     for (int i = 0; i < Peoplelist.size(); i++)
                {
                    int p=Personlist.get(i).getage()-yourage;
                    if(p<0) p=-p;
                    if(p==d_value) System.out.println(Peoplelist.get(i));
                }   */
                break;
            case 5:
           isTrue = false;
           System.out.println("退出程序!");
                break;
            default:
                System.out.println("输入有误");
            }
        }
    }
    public static int agenear(int age) {
     
       int min=25,d_value=0,k=0;
        for (int i = 0; i <  Peoplelist.size(); i++)
        {
            d_value= Peoplelist.get(i).getage()-age;
            if(d_value<0) d_value=-d_value; 
            if (d_value<min) 
            {
               min=d_value;
               k=i;
            }

         }    return k;
        
     }
    
    }

 

package yu;

public class yu {

    public abstract class  People implements Comparable<People> {
    private String name;
    private String ID;
    private int age;
    private String sex;
    private String birthplace;

    public String getname() {
    return name;
    }
    public void setname(String name) {
    this.name = name;
    }
    public String getID() {
    return ID;
    }
    public void setID(String ID) {
    this.ID= ID;
    }
    public int getage() {

    return age;
    }
    public void setage(int age) {
        // int a = Integer.parseInt(age);
    this.age= age;
    }
    public String getsex() {
    return sex;
    }
    public void setsex(String sex) {
    this.sex= sex;
    }
    public String getbirthplace() {
    return birthplace;
    }
    public void setbirthplace(String birthplace) {
    this.birthplace= birthplace;
    }

    public int compareTo(People o) {
       return this.name.compareTo(o.getname());

    }

    public String toString() {
        return  name+"\t"+sex+"\t"+age+"\t"+ID+"\t"+birthplace+"\n";
        }
    }
}

实验结果:

实验 4:内部类语法验证实验

实验程序 1:

l 编辑、调试运行教材 246 页 - 247 页程序 6-7,结合程序运行结果理解程序;

l 了解内部类的基本用法。

package innerClass;

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;

/**
 * This program demonstrates the use of inner classes.
 * @version 1.11 2015-05-12
 * @author Cay Horstmann
 */
public class InnerClassTest
{
   public static void main(String[] args)
   {
      TalkingClock clock = new TalkingClock(1000, true);
      clock.start();

      // 在按确定之前,程序一直运行
      JOptionPane.showMessageDialog(null, "Quit program?");
      System.exit(0);
   }
}

/**
 * A clock that prints the time in regular intervals.
 */
class TalkingClock
{
   private int interval;
   private boolean beep;

   /**
    * Constructs a talking clock
    * @param interval the interval between messages (in milliseconds)
    * @param beep true if the clock should beep
    */
   public TalkingClock(int interval, boolean beep)
   {
      this.interval = interval;
      this.beep = beep;
   }

   /**
    * Starts the clock.
    */
   public void start()
   {
      ActionListener listener = new TimePrinter();//构造器
      Timer t = new Timer(interval, listener);
      t.start();
   }

   public class TimePrinter implements ActionListener
   {
      public void actionPerformed(ActionEvent event)
      {
         System.out.println("At the tone, the time is " + new Date());
         if (beep) Toolkit.getDefaultToolkit().beep();
      }
   }
}

 实验结果:

实验程序 2:

l 编辑、调试运行教材 254 页程序 6-8,结合程序运行结果理解程序;

l 了解匿名内部类的用法。

package anonymousInnerClass;

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;

/**
 * This program demonstrates anonymous inner classes.
 * @version 1.11 2015-05-12
 * @author Cay Horstmann
 */
public class AnonymousInnerClassTest
{
   public static void main(String[] args)
   {
      TalkingClock clock = new TalkingClock();//TalkingClock类声明为私有的
      clock.start(1000, true);

      // keep program running until user selects "Ok"
      JOptionPane.showMessageDialog(null, "Quit program?");
      System.exit(0);
   }
}

/**
 * A clock that prints the time in regular intervals.
 */
class TalkingClock
{
   /**
    * Starts the clock.
    * @param interval the interval between messages (in milliseconds)
    * @param beep true if the clock should beep
    */
   public void start(int interval, boolean beep)
   {
      ActionListener listener = new ActionListener()
         {
            public void actionPerformed(ActionEvent event)
            {
               System.out.println("At the tone, the time is " + new Date());
               if (beep) Toolkit.getDefaultToolkit().beep();
               //外围类引用.
            }
         };
      Timer t = new Timer(interval, listener);
      t.start();
   }
}

实验结果:

 

实验程序 3:

l 在 elipse IDE 中调试运行教材 257 页 - 258 页程序 6-9,结合程序运行结果理解程序;

l 了解静态内部类的用法。

package staticInnerClass;

/**
 * This program demonstrates the use of static inner classes.
 * @version 1.02 2015-05-12
 * @author Cay Horstmann
 */
public class StaticInnerClassTest
{
   public static void main(String[] args)
   {
      double[] d = new double[20];
      for (int i = 0; i < d.length; i++)
         d[i] = 100 * Math.random();
      ArrayAlg.Pair p = ArrayAlg.minmax(d);
      System.out.println("min = " + p.getFirst());
      System.out.println("max = " + p.getSecond());
   }
}

class ArrayAlg
{
   /**
    * A pair of floating-point numbers
    */
   public static class Pair
   {
      private double first;
      private double second;

      /**
       * Constructs a pair from two floating-point numbers
       * @param f the first number
       * @param s the second number
       */
      public Pair(double f, double s)
      {
         first = f;
         second = s;
      }

      /**
       * Returns the first number of the pair
       * @return the first number
       */
      public double getFirst()
      {
         return first;
      }

      /**
       * Returns the second number of the pair
       * @return the second number
       */
      public double getSecond()
      {
         return second;
      }
   }

   /**
    * Computes both the minimum and the maximum of an array
    * @param values an array of floating-point numbers
    * @return a pair whose first element is the minimum and whose second element
    * is the maximum
    */
   public static Pair minmax(double[] values)
   {
      double min = Double.POSITIVE_INFINITY;
      double max = Double.NEGATIVE_INFINITY;
      for (double v : values)
      {
         if (min > v) min = v;
         if (max < v) max = v;
      }
      return new Pair(min, max);
   }
}

实验结果:

实验总结:

       通过这章的学习我了解了接口的使用和他的功能,学会了 Lambda 表达式与内部类。也学会了建立浅拷贝与深拷贝,总的来说本章的知识点还是挺多的。以后我会继续努力,争取敲更多好的代码。

201771010106 东文财《面向对象程序设计(java)》实验 10

201771010106 东文财《面向对象程序设计(java)》实验 10

实验十  泛型程序设计技术

实验时间 2018-11-4

一、理论知识

1、JDK 5.0 中增加的泛型类型,是 Java 语言中类型安全的一次重要改进。

2、 泛型:也称参数化类型 (parameterized type),就是在定义类、接口和方法时,通过类型参数指示将要处理的对象类型。(如 ArrayList 类)

3、泛型程序设计(Generic programming):编写代码可以被很多不同类型的对象所重用。

4、一个泛型类(generic class)就是具有一个或多个类型变量的类,即创建用类型作为参数的类。如一个泛型类定义格式如下:class Generics<K,V>其中的 K 和 V 是类中的可变类型参数。

5、Pair 类引入了一个类型变量 T,用尖括号(<>)括起来,并放在类名的后面。

6、 泛型类可以有多个类型变量。例如:public class Pair<T, U> { … }

7、 类定义中的类型变量用于指定方法的返回类型以及域、局部变量的类型。

8、 泛型方法

(1) 除了泛型类外,还可以只单独定义一个方法作为泛型方法,用于指定方法参数或者返回值为泛型类型,留待方法调用时确定。

(2) 泛型方法可以声明在泛型类中,也可以声明在普通类中。

二、实验部分

1、实验目的与要求

(1) 理解泛型概念;

(2) 掌握泛型类的定义与使用;

(3) 掌握泛型方法的声明与使用;

(4) 掌握泛型接口的定义与实现;

(5) 了解泛型程序设计,理解其用途。

2、实验内容和步骤

实验 1 导入第 8 章示例程序,测试程序并进行代码注释。

测试程序 1:

编辑、调试、运行教材 311312 代码,结合程序运行结果理解程序;

在泛型类定义及使用代码处添加注释;

掌握泛型类的定义及使用。 

package pair1;

/**
 * @version 1.00 2004-05-10
 * @author Cay Horstmann
 */
public class Pair<T> //定义公共类,Pair类引入了一个类型变量T,用于指定方法的返回类型以及域、局部变量的类型。
{
   private T first;
   private T second;

   public Pair() { first = null; second = null; }
   public Pair(T first, T second) { this.first = first;  this.second = second; }

   public T getFirst() { return first; }
   public T getSecond() { return second; }

   public void setFirst(T newValue) { first = newValue; }
   public void setSecond(T newValue) { second = newValue; }
}

 

package pair1;

/**
 * @version 1.01 2012-01-26
 * @author Cay Horstmann
 */
public class PairTest1//定义公共类
{
   public static void main(String[] args)
   {
      String[] words = { "Mary", "had", "a", "little", "lamb" };
      Pair<String> mm = ArrayAlg.minmax(words);
      System.out.println("min = " + mm.getFirst());
      System.out.println("max = " + mm.getSecond());
   }
}

class ArrayAlg//另一个类
{
   /**
    * Gets the minimum and maximum of an array of strings.
    * @param a an array of strings
    * @return a pair with the min and max value, or null if a is null or empty
    */
   public static Pair<String> minmax(String[] a)
   {
      if (a == null || a.length == 0) return null;//条件判断语句
      String min = a[0];
      String max = a[0];
      for (int i = 1; i < a.length; i++)//for循环语句
      {
         if (min.compareTo(a[i]) > 0) min = a[i];
         if (max.compareTo(a[i]) < 0) max = a[i];
      }
      return new Pair<>(min, max);
   }
}

实验结果:

测试程序 2:

编辑、调试运行教材 315 PairTest2,结合程序运行结果理解程序;

在泛型程序设计代码处添加相关注释;

掌握泛型方法、泛型变量限定的定义及用途。

package pair2;

/**
 * @version 1.00 2004-05-10
 * @author Cay Horstmann
 */
public class Pair<T> 
{
   private T first;
   private T second;

   public Pair() { first = null; second = null; }
   public Pair(T first, T second) { this.first = first;  this.second = second; }

   public T getFirst() { return first; }
   public T getSecond() { return second; }

   public void setFirst(T newValue) { first = newValue; }
   public void setSecond(T newValue) { second = newValue; }
}

 

package pair2;

import java.time.*;

/**
 * @version 1.02 2015-06-21
 * @author Cay Horstmann
 */
public class PairTest2
{
   public static void main(String[] args)
   {
      LocalDate[] birthdays = 
         { 
            LocalDate.of(1906, 12, 9), // G. Hopper
            LocalDate.of(1815, 12, 10), // A. Lovelace
            LocalDate.of(1903, 12, 3), // J. von Neumann
            LocalDate.of(1910, 6, 22), // K. Zuse
         };
      Pair<LocalDate> mm = ArrayAlg.minmax(birthdays);
      System.out.println("min = " + mm.getFirst());
      System.out.println("max = " + mm.getSecond());
   }
}

class ArrayAlg
{
   /**
      Gets the minimum and maximum of an array of objects of type T.
      @param a an array of objects of type T
      @return a pair with the min and max value, or null if a is 
      null or empty
   */
   public static <T extends Comparable> Pair<T> minmax(T[] a) 
   {
      if (a == null || a.length == 0) return null;
      T min = a[0];
      T max = a[0];
      for (int i = 1; i < a.length; i++)
      {
         if (min.compareTo(a[i]) > 0) min = a[i];
         if (max.compareTo(a[i]) < 0) max = a[i];
      }
      return new Pair<>(min, max);
   }
}

实验结果:

测试程序 3:

用调试运行教材 335 PairTest3,结合程序运行结果理解程序;

了解通配符类型的定义及用途。

package pair3;

import java.time.*;

public class Employee
{  
   private String name;
   private double salary;
   private LocalDate hireDay;

   public Employee(String name, double salary, int year, int month, int day)
   {
      this.name = name;
      this.salary = salary;
      hireDay = LocalDate.of(year, month, day);
   }

   public String getName()
   {
      return name;
   }

   public double getSalary()
   {  
      return salary;
   }

   public LocalDate getHireDay()
   {  
      return hireDay;
   }

   public void raiseSalary(double byPercent)
   {  
      double raise = salary * byPercent / 100;
      salary += raise;
   }
}

 

package pair3;

public class Manager extends Employee
{  
   private double bonus;

   /**
      @param name the employee''s name
      @param salary the salary
      @param year the hire year
      @param month the hire month
      @param day the hire day
   */
   public Manager(String name, double salary, int year, int month, int day)
   {  
      super(name, salary, year, month, day);
      bonus = 0;
   }

   public double getSalary()
   { 
      double baseSalary = super.getSalary();
      return baseSalary + bonus;
   }

   public void setBonus(double b)
   {  
      bonus = b;
   }

   public double getBonus()
   {  
      return bonus;
   }
}

 

package pair3;

/**
 * @version 1.00 2004-05-10
 * @author Cay Horstmann
 */
public class Pair<T> 
{
   private T first;
   private T second;

   public Pair() { first = null; second = null; }
   public Pair(T first, T second) { this.first = first;  this.second = second; }

   public T getFirst() { return first; }
   public T getSecond() { return second; }

   public void setFirst(T newValue) { first = newValue; }
   public void setSecond(T newValue) { second = newValue; }
}

 

package pair3;

/**
 * @version 1.01 2012-01-26
 * @author Cay Horstmann
 */
public class PairTest3
{
   public static void main(String[] args)
   {
      Manager ceo = new Manager("Gus Greedy", 800000, 2003, 12, 15);
      Manager cfo = new Manager("Sid Sneaky", 600000, 2003, 12, 15);
      Pair<Manager> buddies = new Pair<>(ceo, cfo);      
      printBuddies(buddies);

      ceo.setBonus(1000000);
      cfo.setBonus(500000);
      Manager[] managers = { ceo, cfo };

      Pair<Employee> result = new Pair<>();
      minmaxBonus(managers, result);
      System.out.println("first: " + result.getFirst().getName() 
         + ", second: " + result.getSecond().getName());
      maxminBonus(managers, result);
      System.out.println("first: " + result.getFirst().getName() 
         + ", second: " + result.getSecond().getName());
   }

   public static void printBuddies(Pair<? extends Employee> p)
   {
      Employee first = p.getFirst();
      Employee second = p.getSecond();
      System.out.println(first.getName() + " and " + second.getName() + " are buddies.");
   }

   public static void minmaxBonus(Manager[] a, Pair<? super Manager> result)
   {
      if (a.length == 0) return;
      Manager min = a[0];
      Manager max = a[0];
      for (int i = 1; i < a.length; i++)
      {
         if (min.getBonus() > a[i].getBonus()) min = a[i];
         if (max.getBonus() < a[i].getBonus()) max = a[i];
      }
      result.setFirst(min);
      result.setSecond(max);
   }

   public static void maxminBonus(Manager[] a, Pair<? super Manager> result)
   {
      minmaxBonus(a, result);
      PairAlg.swapHelper(result); // OK--swapHelper captures wildcard type
   }
   // Can''t write public static <T super manager> ...
}

class PairAlg
{
   public static boolean hasNulls(Pair<?> p)
   {
      return p.getFirst() == null || p.getSecond() == null;
   }

   public static void swap(Pair<?> p) { swapHelper(p); }

   public static <T> void swapHelper(Pair<T> p)
   {
      T t = p.getFirst();
      p.setFirst(p.getSecond());
      p.setSecond(t);
   }
}

实验结果:

实验 2编程练习:

编程练习 1:实验九编程题总结

实验九编程练习 1 总结(从程序总体结构说明、模块说明,目前程序设计存在的困难与问题三个方面阐述)。

 总体结构:

类 people

1、读入文件等

2、定义了查找人员信息的方法

3、分 5 个 case 来分别说年龄大小、等。

出现问题:

过程中出现了很多问题,主要原因还是在于自己的粗心和对一些知识的掌握不够,不过在和同学们的交流和学习中得以解决,以后我会接续努力的。

package gh;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    import java.util.Scanner;
    import java.util.Collections;

    public class tt {

        public static People findPeopleByname(String name) {
            People flag = null;
            for (People people : peoplelist) {
                if(people.getName().equals(name)) {
                    flag = people;
                }
            }
            return flag;

        }

        public static People findPeopleByid(String id) {
            People flag = null;
            for (People people : peoplelist) {
                if(people.getnumber().equals(id)) {
                    flag = people;
                }
            }
            return flag;

        }
         
        private static ArrayList<People> agenear(int yourage) {
            // TODO Auto-generated method stub
            int j=0,min=53,d_value=0,k = 0;
            ArrayList<People> plist = new ArrayList<People>();
            for (int i = 0; i < peoplelist.size(); i++) {
                d_value = peoplelist.get(i).getage() > yourage ? 
                        peoplelist.get(i).getage() - yourage : yourage - peoplelist.get(i).getage() ;
                k = d_value < min ? i : k;
                min = d_value < min ? d_value : min;
            }
            for(People people : peoplelist) {
                if(people.getage() == peoplelist.get(k).getage()) {
                    plist.add(people);
                }
            }
            return plist;
        }

        private static ArrayList<People> peoplelist; 
        
        public static void main(String[] args) //throws  IOException
        {
            peoplelist = new ArrayList<People>();
            Scanner scanner = new Scanner(System.in);
            File file = new File("D:\\身份证号.txt");
            try {
                FileInputStream files = new FileInputStream(file);
                BufferedReader in = new BufferedReader(new InputStreamReader(files));
                String temp = null;
                while ((temp = in.readLine()) != null) {
                    
                    String[] information = temp.split("[ ]+");
                    People people = new People();
                    people.setName(information[0]);
                    people.setnumber(information[1]);
                    int A = Integer.parseInt(information[3]);
                    people.setage(A);
                    people.setsex(information[2]);
                    for(int j = 4; j<information.length;j++) {
                        people.setplace(information[j]);
                    }
                    peoplelist.add(people);

                }
            } catch (FileNotFoundException e) {
                System.out.println("文件未找到");
                e.printStackTrace();
            } catch (IOException e) {
                System.out.println("文件读取错误");
                e.printStackTrace();
            }
            boolean isTrue = true;
            while (isTrue) {

                System.out.println("******************************************");
                System.out.println("   1.按姓名典序输出人员信息");
                System.out.println("   2.查询最大年龄人员信息");
                System.out.println("   3.查询最小年龄人员信息");
                System.out.println("   4.输入你的年龄,查询身份证号.txt中年龄与你最近的人");
                System.out.println("   5.查询人员中是否有你的同乡");
                System.out.println("   6.退出");
                System.out.println("******************************************");
                int nextInt = scanner.nextInt();
                switch (nextInt) {
                case 1:
                    Collections.sort(peoplelist);
                    System.out.println(peoplelist.toString());
                    break;
                case 2:
                    int max=0;
                    int j,k1 = 0;
                    for(int i=1;i<peoplelist.size();i++)
                    {
                        j = peoplelist.get(i).getage();
                       if(j>max)
                       {
                           max = j; 
                           k1 = i;
                       }
                      
                    }  
                    System.out.println("年龄最大:"+peoplelist.get(k1));
                    break;
                case 3:
                    int min = 100;
                    int j1,k2 = 0;
                    for(int i=1;i<peoplelist.size();i++)
                    {
                        j1 = peoplelist.get(i).getage();
                        if(j1<min)
                        {
                            min = j1; 
                            k2 = i;
                        }

                     } 
                    System.out.println("年龄最小:"+peoplelist.get(k2));
                    break;
                case 4:
                    System.out.println("年龄:");
                    int input_age = scanner.nextInt();
                    ArrayList<People> plist = new ArrayList<People>();
                    plist = agenear(input_age);
                    for(People people : plist) {
                        System.out.println(people.toString());
                    }
                    break;
                case 5:
                    System.out.println("请输入省份");
                    String find = scanner.next();        
                    for (int i = 0; i <peoplelist.size(); i++) 
                    {
                        String [] place = peoplelist.get(i).getplace().split("\t");
                        for(String temp : place) {
                            if(find.equals(temp)) {
                                System.out.println("你的同乡是    "+peoplelist.get(i));
                                break;
                            }
                        }
                        
                    } 
                    break;
                case 6:
                    isTrue = false;
                    System.out.println("byebye!");
                    break;
                default:
                    System.out.println("输入有误");
                }
            }
        }

    }
}

实验九编程练习 2 总结(从程序总体结构说明、模块说明,目前程序设计存在的困难与问题三个方面阐述)。

 

总体结构:

类 main

1、程序中的文件读取等

出现问题:

1. 没有定义文件输出的路径,找输出文件不简单。

解决方法:只需定义路径即可如:

("E:\\壁纸\\海贼王\\text.txt");

 

 

package rt;


    import java.io.FileNotFoundException;
    import java.io.PrintWriter;
    import java.util.Scanner;
    public class tt {
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            tt1 computing=new tt1();
            PrintWriter output = null;
            try {
                output = new PrintWriter("tt.txt");
            } catch (Exception e) {
            }
            int sum = 0;

            for (int i = 1; i < 11; i++) {
                int a = (int) Math.round(Math.random() * 100);
                int b = (int) Math.round(Math.random() * 100);
                int s = (int) Math.round(Math.random() * 3);
            switch(s)
            {
               case 1:
                   System.out.println(i+": "+a+"/"+b+"=");
                   while(b==0){  
                       b = (int) Math.round(Math.random() * 100); 
                       }
                   double c = in.nextDouble();
                   output.println(a+"/"+b+"="+c);
                   if (c == (double)computing.division(a, b)) {
                       sum += 10;
                       System.out.println("正确");
                   }
                   else {
                       System.out.println("错误");
                   }
                
                   break;
                
               case 2:
                   System.out.println(i+": "+a+"*"+b+"=");
                   int c1 = in.nextInt();
                   output.println(a+"*"+b+"="+c1);
                   if (c1 == computing.multiplication(a, b)) {
                       sum += 10;
                       System.out.println("正确");
                   }
                   else {
                       System.out.println("错误");
                   }
                   break;
               case 3:
                   System.out.println(i+": "+a+"+"+b+"=");
                   int c2 = in.nextInt();
                   output.println(a+"+"+b+"="+c2);
                   if (c2 == computing.addition(a, b)) {
                       sum += 10;
                       System.out.println("正确");
                   }
                   else {
                       System.out.println("错误");
                   }
                   
                   break ;
               case 4:
                   System.out.println(i+": "+a+"-"+b+"=");
                   int c3 = in.nextInt();
                   output.println(a+"-"+b+"="+c3);
                   if (c3 == computing.subtraction(a, b)) {
                       sum += 10;
                       System.out.println("正确");
                   }
                   else {
                       System.out.println("错误");
                   }
                   break ;

                   } 
        
              }
            System.out.println("成绩:"+sum+"分");
            output.println("成绩:"+sum+"分");
            output.close();
             
        }
    }
    class tt1
    {
           private int a;
           private int b;
            public int  addition(int a,int b)
            {
                return a+b;
            }
            public int  subtraction(int a,int b)
            {
                if((a-b)<0)
                    return 0;
                else
                return a-b;
            }
            public int   multiplication(int a,int b)
            {
                return a*b;
            }
            public int   division(int a,int b)
            {
                if(b!=0)
                return a/b;    
                else
            return 0;
            }

            
    }

 

编程练习 2:采用泛型程序设计技术改进实验九编程练习 2,使之可处理实数四则运算,其他要求不变。

package hh;

public class jj<T> {
private T a;
private T b;
public jj() {
a = null;
b = null;
}

public jj(T a, T b) {
this.a = a;
this.b = b;
}
public int jj1(int a,int b)
{
return a+b;
}
public int jj2(int a,int b)
{
return a-b;
}
public int jj3(int a,int b)
{
return a*b;
}
public int jj4(int a,int b)
{
if(b!=0)
return a/b;
else return 0;
}

}

 

package hh;
    import java.io.FileNotFoundException;
    import java.io.PrintWriter;
    import java.util.Scanner;


    public class kk {
        public static void main(String[] args) {

            Scanner in = new Scanner(System.in);
            jj counter=new jj();
            PrintWriter out = null;
            try {
                out = new PrintWriter("E:\\壁纸\\海贼王\\text.txt");
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            int sum = 0;

            
            
            for (int i = 0; i <10; i++) {
                int a = (int) Math.round(Math.random() * 100);
                int b = (int) Math.round(Math.random() * 100);
                int m= (int) Math.round(Math.random() * 3);

                
               switch(m)
               {
               case 0:
                   System.out.println(a + "+" + b + "=");
                   int d0 = in.nextInt();
                   out.println(a + "+" + b + "=" + d0);
                   if (d0 == counter.jj1(a, b)) {
                       sum += 10;
                       System.out.println("正确");
                   } else {
                       System.out.println("错误");
                   }
                   break;
               case 1:
                   while (a < b) {
                       int x = a;
                       a = b;
                       b = x;
                   }
                   System.out.println(a + "-" + b + "=");
                   int c1 = in.nextInt();
                   out.println(a + "-" + b + "=" + c1);
                   if (c1 == counter.jj2(a, b)) {
                       sum += 10;
                       System.out.println("正确");
                   } else {
                       System.out.println("错误");
                   }
                   break;
               case 2:
                   System.out.println(a + "*" + b + "=");
                   int c2 = in.nextInt();
                   out.println(a + "*" + b + "=" + c2);
                   if (c2 ==counter.jj3(a, b)) {
                       sum += 10;
                       System.out.println("正确");
                   } else {
                       System.out.println("错误");
                   }
                   break;
               case 3:
                   while (b == 0 || a % b != 0) {
                       a = (int) Math.round(Math.random() * 100);
                       b = (int) Math.round(Math.random() * 100);
                   }
                   System.out.println(a + "/" + b + "=");
                   int c3 = in.nextInt();
                   out.println(a + "/" + b + "=" + c3);
                   if (c3 == counter.jj4(a, b)) {
                       sum += 10;
                       System.out.println("正确");
                   } else {
                       System.out.println("错误");
                   }
                   break;

               }

         
    }
            System.out.println("成绩"+sum);
            out.println("成绩:"+sum);
             out.close();

             
        }
        }

实验结果:

实验总结:

   本章我们主要学习了泛型程序设计,使用泛型机制编写的程序代码要比那些杂乱地使用 Object 变量,然后再进行强行类型转换的代码具有更好的安全性和可读性。反省对于集合类尤其有用。通过课后一些简单程序的编译,运行,知道了如何定义简单的泛型类,和他的一些用法。希望在以后的编程中我会多多的用到这些学过的知识。

201771010106 东文财《面向对象程序设计(java)》实验 9

201771010106 东文财《面向对象程序设计(java)》实验 9

实验九 异常、断言与日志

实验时间 2018-10-25

1、实验目的与要求

(1) 掌握 java 异常处理技术;

(2) 了解断言的用法;

(3) 了解日志的用途;

(4) 掌握程序基础调试技巧;

2、实验内容和步骤

实验 1:用命令行与 IDE 两种环境下编辑调试运行源程序 ExceptionDemo1、ExceptionDemo2,结合程序运行结果理解程序,掌握未检查异常和已检查异常的区别。

// 异常示例 1

public class ExceptionDemo1 {

public static void main(String args[]) {

int a = 0;

System.out.println(5 / a);

}

}

// 异常示例 2

import java.io.*;

 

public class ExceptionDemo2 {

public static void main(String args[])

     {

          FileInputStream fis=new FileInputStream("text.txt");//JVM 自动生成异常对象

          int b;

          while((b=fis.read())!=-1)

          {

              System.out.print(b);

          }

          fis.close();

      }

}

package tt;
public class ExceptionDemo1 {

public static void main(String args[]) {

int a = 0;

System.out.println(5 / a);

}

}

 

package tt;
import java.io.*;



public class ExceptionDemo2 {

public static void main(String args[])

     {

          FileInputStream fis = null;
        try {
            fis = new FileInputStream("C:\\Users\\LENOVO\\Desktop\\text.txt");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }//JVM自动生成异常对象

          int b;

          try {
            while((b=fis.read())!=-1)

              {

                  System.out.print(b);

              }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

          try {
            fis.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

      }

}
实验结果:

实验 2 导入以下示例程序,测试程序并进行代码注释。

测试程序 1:

l 在 elipse IDE 中编辑、编译、调试运行教材 281 页 7-1,结合程序运行结果理解程序;

l 在程序中相关代码处添加新知识的注释;

l 掌握 Throwable 类的堆栈跟踪方法;

package stackTrace;

import java.util.*;

/**
 * A program that displays a trace feature of a recursive method call.
 * @version 1.01 2004-05-10
 * @author Cay Horstmann
 */
public class StackTraceTest
{
   /**
    * Computes the factorial of a number
    * @param n a non-negative integer
    * @return n! = 1 * 2 * . . . * n
    */
   public static int factorial(int n)
   {
      System.out.println("factorial(" + n + "):");
      Throwable t = new Throwable();//构造一个Throwable 对象
      StackTraceElement[] frames = t.getStackTrace();//获得构造这个对象时调用的对战的跟踪
      for (StackTraceElement f : frames)
         System.out.println(f);
      int r;
      if (n <= 1) r = 1;
      else r = n * factorial(n - 1);
      System.out.println("return " + r);
      return r;
   }

   public static void main(String[] args)
   {
      Scanner in = new Scanner(System.in);
      System.out.print("Enter n: ");
      int n = in.nextInt();
      factorial(n);
   }
}

实验结果:

测试程序 2:

l Java 语言的异常处理积极处理方法和消极处理两种方式

l 下列两个简答程序范例给出了两种异常处理的代码格式。在 elipse IDE 中编辑、调试运行源程序 ExceptionalTest.java,将程序中的 text 文件更换为身份证号.txt,要求将文件内容读入内容,并在控制台显示;

l 掌握两种异常处理技术的特点。

// 积极处理方式  

import java.io.*;

 

class ExceptionTest {

public static void main (string args[])

   {

       try{

       FileInputStream fis=new FileInputStream("text.txt");

       }

       catchFileNotFoundExcption e

     {   ……  }

……

    }

}

// 消极处理方式

 

import java.io.*;

class ExceptionTest {

public static void main (string args[]) throws  FileNotFoundExcption

     {

      FileInputStream fis=new FileInputStream("text.txt");

     }

}

package tt;

//积极处理方式  
import java.io.*;
import java.io.BufferedReader;
import java.io.FileReader;

class ExceptionTest {
    public static void main (String args[])
 {
        File fis=new File("C:\\\\Users\\\\LENOVO\\\\Desktop\\\\身份证号.txt");
     try{
         

         FileReader fr = new FileReader(fis);
         BufferedReader br = new BufferedReader(fr);
         try {
             String s, s2 = new String();
             while ((s = br.readLine()) != null) {
                 s2 += s + "\n ";
             }
             br.close();
             System.out.println(s2);
         } catch (IOException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         }
     } catch (FileNotFoundException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
     }

  }
}

 

package tt;

//消极处理方式

import java.io.*;
class ExceptionDemo2 {
    public static void main (String args[]) throws  IOException
       {
        File fis=new File("C:\\Users\\LENOVO\\Desktop\\身份证号.txt");
        FileReader fr = new FileReader(fis);
        BufferedReader br = new BufferedReader(fr);
        String s, s2 = new String();

            while ((s = br.readLine()) != null) {
                s2 += s + "\n ";
            }
            br.close();
            System.out.println(s2);
       }
}

实验结果:

实验 3: 编程练习

练习 1

编制一个程序,将身份证号.txt 中的信息读入到内存中;

l 按姓名字典序输出人员信息;

l 查询最大年龄的人员信息;

l 查询最小年龄人员信息;

输入你的年龄,查询身份证号.txt 中年龄与你最近人的姓名、身份证号、年龄、性别和出生地;

l 查询人员中是否有你的同乡;

l 在以上程序适当位置加入异常捕获代码。

注:以下实验课后完成

 

package gh;



    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    import java.util.Scanner;
    import java.util.Collections;

    public class tt {

        public static People findPeopleByname(String name) {
            People flag = null;
            for (People people : peoplelist) {
                if(people.getName().equals(name)) {
                    flag = people;
                }
            }
            return flag;

        }

        public static People findPeopleByid(String id) {
            People flag = null;
            for (People people : peoplelist) {
                if(people.getnumber().equals(id)) {
                    flag = people;
                }
            }
            return flag;

        }
         
        private static ArrayList<People> agenear(int yourage) {
            // TODO Auto-generated method stub
            int j=0,min=53,d_value=0,k = 0;
            ArrayList<People> plist = new ArrayList<People>();
            for (int i = 0; i < peoplelist.size(); i++) {
                d_value = peoplelist.get(i).getage() > yourage ? 
                        peoplelist.get(i).getage() - yourage : yourage - peoplelist.get(i).getage() ;
                k = d_value < min ? i : k;
                min = d_value < min ? d_value : min;
            }
            for(People people : peoplelist) {
                if(people.getage() == peoplelist.get(k).getage()) {
                    plist.add(people);
                }
            }
            return plist;
        }

        private static ArrayList<People> peoplelist; 
        
        public static void main(String[] args) //throws  IOException
        {
            peoplelist = new ArrayList<People>();
            Scanner scanner = new Scanner(System.in);
            File file = new File("D:\\身份证号.txt");
            try {
                FileInputStream files = new FileInputStream(file);
                BufferedReader in = new BufferedReader(new InputStreamReader(files));
                String temp = null;
                while ((temp = in.readLine()) != null) {
                    
                    String[] information = temp.split("[ ]+");
                    People people = new People();
                    people.setName(information[0]);
                    people.setnumber(information[1]);
                    int A = Integer.parseInt(information[3]);
                    people.setage(A);
                    people.setsex(information[2]);
                    for(int j = 4; j<information.length;j++) {
                        people.setplace(information[j]);
                    }
                    peoplelist.add(people);

                }
            } catch (FileNotFoundException e) {
                System.out.println("文件未找到");
                e.printStackTrace();
            } catch (IOException e) {
                System.out.println("文件读取错误");
                e.printStackTrace();
            }
            boolean isTrue = true;
            while (isTrue) {

                System.out.println("******************************************");
                System.out.println("   1.按姓名典序输出人员信息");
                System.out.println("   2.查询最大年龄人员信息");
                System.out.println("   3.查询最小年龄人员信息");
                System.out.println("   4.输入你的年龄,查询身份证号.txt中年龄与你最近的人");
                System.out.println("   5.查询人员中是否有你的同乡");
                System.out.println("   6.退出");
                System.out.println("******************************************");
                int nextInt = scanner.nextInt();
                switch (nextInt) {
                case 1:
                    Collections.sort(peoplelist);
                    System.out.println(peoplelist.toString());
                    break;
                case 2:
                    int max=0;
                    int j,k1 = 0;
                    for(int i=1;i<peoplelist.size();i++)
                    {
                        j = peoplelist.get(i).getage();
                       if(j>max)
                       {
                           max = j; 
                           k1 = i;
                       }
                      
                    }  
                    System.out.println("年龄最大:"+peoplelist.get(k1));
                    break;
                case 3:
                    int min = 100;
                    int j1,k2 = 0;
                    for(int i=1;i<peoplelist.size();i++)
                    {
                        j1 = peoplelist.get(i).getage();
                        if(j1<min)
                        {
                            min = j1; 
                            k2 = i;
                        }

                     } 
                    System.out.println("年龄最小:"+peoplelist.get(k2));
                    break;
                case 4:
                    System.out.println("年龄:");
                    int input_age = scanner.nextInt();
                    ArrayList<People> plist = new ArrayList<People>();
                    plist = agenear(input_age);
                    for(People people : plist) {
                        System.out.println(people.toString());
                    }
                    break;
                case 5:
                    System.out.println("请输入省份");
                    String find = scanner.next();        
                    for (int i = 0; i <peoplelist.size(); i++) 
                    {
                        String [] place = peoplelist.get(i).getplace().split("\t");
                        for(String temp : place) {
                            if(find.equals(temp)) {
                                System.out.println("你的同乡是    "+peoplelist.get(i));
                                break;
                            }
                        }
                        
                    } 
                    break;
                case 6:
                    isTrue = false;
                    System.out.println("byebye!");
                    break;
                default:
                    System.out.println("输入有误");
                }
            }
        }

    }
}

实验结果:

练习 2

l 编写一个计算器类,可以完成加、减、乘、除的操作;

利用计算机类,设计一个小学生 100 以内数的四则运算练习程序,由计算机随机产生 10 道加减乘除练习题,学生输入答案,由程序检查答案是否正确,每道题正确计 10 分,错误不计分,10 道题测试结束后给出测试总分;

将程序中测试练习题及学生答题结果输出到文件,文件名为 test.txt

l 在以上程序适当位置加入异常捕获代码。

package rt;


    import java.io.FileNotFoundException;
    import java.io.PrintWriter;
    import java.util.Scanner;
    public class tt {
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            tt1 computing=new tt1();
            PrintWriter output = null;
            try {
                output = new PrintWriter("tt.txt");
            } catch (Exception e) {
            }
            int sum = 0;

            for (int i = 1; i < 11; i++) {
                int a = (int) Math.round(Math.random() * 100);
                int b = (int) Math.round(Math.random() * 100);
                int s = (int) Math.round(Math.random() * 3);
            switch(s)
            {
               case 1:
                   System.out.println(i+": "+a+"/"+b+"=");
                   while(b==0){  
                       b = (int) Math.round(Math.random() * 100); 
                       }
                   double c = in.nextDouble();
                   output.println(a+"/"+b+"="+c);
                   if (c == (double)computing.division(a, b)) {
                       sum += 10;
                       System.out.println("正确");
                   }
                   else {
                       System.out.println("错误");
                   }
                
                   break;
                
               case 2:
                   System.out.println(i+": "+a+"*"+b+"=");
                   int c1 = in.nextInt();
                   output.println(a+"*"+b+"="+c1);
                   if (c1 == computing.multiplication(a, b)) {
                       sum += 10;
                       System.out.println("正确");
                   }
                   else {
                       System.out.println("错误");
                   }
                   break;
               case 3:
                   System.out.println(i+": "+a+"+"+b+"=");
                   int c2 = in.nextInt();
                   output.println(a+"+"+b+"="+c2);
                   if (c2 == computing.addition(a, b)) {
                       sum += 10;
                       System.out.println("正确");
                   }
                   else {
                       System.out.println("错误");
                   }
                   
                   break ;
               case 4:
                   System.out.println(i+": "+a+"-"+b+"=");
                   int c3 = in.nextInt();
                   output.println(a+"-"+b+"="+c3);
                   if (c3 == computing.subtraction(a, b)) {
                       sum += 10;
                       System.out.println("正确");
                   }
                   else {
                       System.out.println("错误");
                   }
                   break ;

                   } 
        
              }
            System.out.println("成绩:"+sum+"分");
            output.println("成绩:"+sum+"分");
            output.close();
             
        }
    }
    class tt1
    {
           private int a;
           private int b;
            public int  addition(int a,int b)
            {
                return a+b;
            }
            public int  subtraction(int a,int b)
            {
                if((a-b)<0)
                    return 0;
                else
                return a-b;
            }
            public int   multiplication(int a,int b)
            {
                return a*b;
            }
            public int   division(int a,int b)
            {
                if(b!=0)
                return a/b;    
                else
            return 0;
            }

            
    }

实验结果:

 

实验 4:断言、日志、程序调试技巧验证实验。

实验程序 1

// 断言程序示例

public class AssertDemo {

    public static void main(String[] args) {        

        test1(-5);

        test2(-3);

    }

    

    private static void test1(int a){

        assert a > 0;

        System.out.println(a);

    }

    private static void test2(int a){

       assert a > 0 : "something goes wrong here, a cannot be less than 0";

        System.out.println(a);

    }

}

 

l 在 elipse 下调试程序 AssertDemo,结合程序运行结果理解程序;

l 注释语句 test1 (-5); 后重新运行程序,结合程序运行结果理解程序;

l 掌握断言的使用特点及用法。

package rt;

public class tt {



        public static void main(String[] args) {       

           // test1(-5);

            test2(-3);

        }

       

        private static void test1(int a){

            assert a > 0;

            System.out.println(a);

        }

        private static void test2(int a){

           assert a > 0 : "something goes wrong here, a cannot be less than 0";

            System.out.println(a);

        }

    }

 实验结果:

实验程序 2:

l 用 JDK 命令调试运行教材 298 -300 页程序 7-2,结合程序运行结果理解程序;

l 并掌握 Java 日志系统的用途及用法。

package logging;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.logging.*;
import javax.swing.*;

/**
 * A modification of the image viewer program that logs various events.
 * @version 1.03 2015-08-20
 * @author Cay Horstmann
 */
public class LoggingImageViewer
{
   public static void main(String[] args)
   {
      if (System.getProperty("java.util.logging.config.class") == null
            && System.getProperty("java.util.logging.config.file") == null)
      {
         try
         {
            Logger.getLogger("com.horstmann.corejava").setLevel(Level.ALL);
            final int LOG_ROTATION_COUNT = 10;
            Handler handler = new FileHandler("%h/LoggingImageViewer.log", 0, LOG_ROTATION_COUNT);
            Logger.getLogger("com.horstmann.corejava").addHandler(handler);
         }
         catch (IOException e)
         {
            Logger.getLogger("com.horstmann.corejava").log(Level.SEVERE,
                  "Can''t create log file handler", e);
         }
      }

      EventQueue.invokeLater(() ->
            {
               Handler windowHandler = new WindowHandler();
               windowHandler.setLevel(Level.ALL);
               Logger.getLogger("com.horstmann.corejava").addHandler(windowHandler);

               JFrame frame = new ImageViewerFrame();
               frame.setTitle("LoggingImageViewer");
               frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

               Logger.getLogger("com.horstmann.corejava").fine("Showing frame");
               frame.setVisible(true);
            });
   }
}

/**
 * The frame that shows the image.
 */
class ImageViewerFrame extends JFrame
{
   private static final int DEFAULT_WIDTH = 300;
   private static final int DEFAULT_HEIGHT = 400;   

   private JLabel label;
   private static Logger logger = Logger.getLogger("com.horstmann.corejava");

   public ImageViewerFrame()
   {
      logger.entering("ImageViewerFrame", "<init>");      
      setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

      // set up menu bar
      JMenuBar menuBar = new JMenuBar();
      setJMenuBar(menuBar);

      JMenu menu = new JMenu("File");
      menuBar.add(menu);

      JMenuItem openItem = new JMenuItem("Open");
      menu.add(openItem);
      openItem.addActionListener(new FileOpenListener());

      JMenuItem exitItem = new JMenuItem("Exit");
      menu.add(exitItem);
      exitItem.addActionListener(new ActionListener()
         {
            public void actionPerformed(ActionEvent event)
            {
               logger.fine("Exiting.");
               System.exit(0);
            }
         });

      // use a label to display the images
      label = new JLabel();
      add(label);
      logger.exiting("ImageViewerFrame", "<init>");
   }

   private class FileOpenListener implements ActionListener
   {
      public void actionPerformed(ActionEvent event)
      {
         logger.entering("ImageViewerFrame.FileOpenListener", "actionPerformed", event);

         // set up file chooser
         JFileChooser chooser = new JFileChooser();
         chooser.setCurrentDirectory(new File("."));

         // accept all files ending with .gif
         chooser.setFileFilter(new javax.swing.filechooser.FileFilter()
            {
               public boolean accept(File f)
               {
                  return f.getName().toLowerCase().endsWith(".gif") || f.isDirectory();
               }

               public String getDescription()
               {
                  return "GIF Images";
               }
            });

         // show file chooser dialog
         int r = chooser.showOpenDialog(ImageViewerFrame.this);

         // if image file accepted, set it as icon of the label
         if (r == JFileChooser.APPROVE_OPTION)
         {
            String name = chooser.getSelectedFile().getPath();
            logger.log(Level.FINE, "Reading file {0}", name);
            label.setIcon(new ImageIcon(name));
         }
         else logger.fine("File open dialog canceled.");
         logger.exiting("ImageViewerFrame.FileOpenListener", "actionPerformed");
      }
   }
}

/**
 * A handler for displaying log records in a window.
 */
class WindowHandler extends StreamHandler
{
   private JFrame frame;

   public WindowHandler()
   {
      frame = new JFrame();
      final JTextArea output = new JTextArea();
      output.setEditable(false);
      frame.setSize(200, 200);
      frame.add(new JScrollPane(output));
      frame.setFocusableWindowState(false);
      frame.setVisible(true);
      setOutputStream(new OutputStream()
         {
            public void write(int b)
            {
            } // not called

            public void write(byte[] b, int off, int len)
            {
               output.append(new String(b, off, len));
            }
         });
   }

   public void publish(LogRecord record)
   {
      if (!frame.isVisible()) return;
      super.publish(record);
      flush();
   }
}

实验结果:

实验程序 3:

l 用 JDK 命令调试运行教材 298 -300 页程序 7-2,结合程序运行结果理解程序;

按课件 66-77 内容练习并掌握 Elipse 的常用调试技术。

实验总结:

      本次实验我的收获还是挺大的,通过一些示例程序的的编译、运行,我对本章的知识有了一定的了解,知道了对于程序中的一些错误的改正方法,也知道了断言的用法和日志的用途。不过本章中依然有一些知识点不是很了解,在今后的学习中我会继续加油,争取搞懂这些不懂的知识点。多多敲代码,希望以后我的编程技术会有很大的进步。

关于苏浪浪 201771010120《面向对象程序设计java》第六章学习总结的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于201771010106 东文财《面向对象程序设计(java)》 实验 6、201771010106 东文财《面向对象程序设计(java)》 实验 8、201771010106 东文财《面向对象程序设计(java)》实验 10、201771010106 东文财《面向对象程序设计(java)》实验 9等相关知识的信息别忘了在本站进行查找喔。

本文标签: