zoukankan      html  css  js  c++  java
  • 王之泰201771010131《面向对象程序设计(java)》第六周学习总结

    第一部分:理论知识学习部分

    第五章

    第五章学习内容主要分为七个模块,分别为:

    1.类、超类和子类;

    a. 类继承的格式: class 新类名extends已有类名。

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

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

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

    d.从一个超类扩展而来的类集合称为继承层次。在继承层次中,某个类到其祖先的路径被称为该类的继承链。

    注:Java不支持多继承。

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

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

    g.抽象类:抽象方法充当着占位的角色,它们的具体实现在子类中。

    抽象类不能被实例化,即不能创建对象,只能产生子类。

    2.Object:所有类的超类;

    a. Object类是Java中所有类的祖先——每一个类都由它扩展而来。在不给出超类的情况下,Java会自动把Object 作为要定义类的超类。

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

    c. Object类中的equals方法用于测试某个对象是否同另一个对象相等。它在Object类中的实现是判断两个对象是否具有相同的引用。如果两个对象具有相同的引用,它们一定是相等的。

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

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

    3.泛型数组列表;

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

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

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

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

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

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

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

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

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

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

    6.枚举类;

    a. 声明枚举类

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

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

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

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

    7.继承设计的技巧。

    a. 将公共操作和域放在超类。

    b.不要使用受保护的域。

    c.使用继承实现“is-a”关系。

    d.除非所有继承的方法都有意义,否则就不要使用继承。

    e.在覆盖方法时,不要改变预期的行为。

    f.使用多态,而非类型信息。

    g.过多地使用反射。

    第二部分:实验部分

    实验六继承定义与使用

    1、实验目的与要求

    (1) 理解继承的定义;

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

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

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

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

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

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

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

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

    2、实验内容和步骤

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

    测试程序1:

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

    2)掌握子类的定义及用法;

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

    程序5-1如下:

     1 package inheritance;
     2 
     3 /**
     4  * This program demonstrates inheritance.
     5  * @version 1.21 2004-02-21
     6  * @author Cay Horstmann
     7  */
     8 public class ManagerTest
     9 {
    10    public static void main(String[] args)
    11    {
    12       // 构建管理者对象
    13       Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15);
    14       boss.setBonus(5000);
    15 
    16       Employee[] staff = new Employee[3];
    17 
    18       // 用管理者和雇员对象填充工作人员数组
    19 
    20       staff[0] = boss;
    21       staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
    22       staff[2] = new Employee("Tommy Tester", 40000, 1990, 3, 15);
    23 
    24       // 打印所有员工对象的信息
    25       for (Employee e : staff)
    26          System.out.println("name=" + e.getName() + ",salary=" + e.getSalary());
    27    }
    28 }

    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类:

     1 package inheritance;
     2 //关键字extends表示继承。表明正在构造一个新类派生于一个已经存在的类。已经存在的类称为超类/基类/或者父类;新类称为子类/派生类/或者孩子类。
     3 public class Manager extends Employee
     4 {
     5    private double bonus;
     6 
     7    /**
     8     * @param name the employee's name
     9     * @param salary the salary
    10     * @param year the hire year
    11     * @param month the hire month
    12     * @param day the hire day
    13     */
    14    public Manager(String name, double salary, int year, int month, int day)
    15    {//下面这句的意思是调用超类中含有n,s,year,month,day参数的构造器。
    16       super(name, salary, year, month, day);
    17       bonus = 0;
    18    }
    19 
    20    public double getSalary()
    21    {  //子类要想访问要想访问超类中的方法需要使用特定的关键字super,
    22        //super调用构造器的语句必须是子类构造器的第一条语句。
    23       double baseSalary = super.getSalary();
    24       return baseSalary + bonus;
    25    }
    26 
    27    public void setBonus(double b)
    28    {
    29       bonus = b;
    30    }
    31 }

    程序运行结果如下:

    程序小结:子类的定义就我个人认为,使用extends关键字完成继承操作就可以了,如下面代码:

    class BaseClass{    //父类
        //......
    }
    class NewClass extends BaseClass{    //子类
        //......
    }

    在构造类时,可以在声明的时候用父类,在具体的构造器时,用子类。新生成的对象是父类类型的对象,也就是说这个对象中目前只有父类的属性和方法,但是,如果子类重写,就应该用子类重写的方法。

     对于面向对象风格程序构造特点,我觉得大体有四个,即:抽象、封装、继承、多态。

    a)封装:就是把一部分或全部属性和部分功能(函数)对外界屏蔽,即从外界(类的大括号之外)看不到,不可知。

      封装两个方面的含义:一是将有关数据和操作代码封装在对象当中,形成一个基本单位,各个对象之间相对独立互不干扰。

                                       二是将对象中某些属性和操作私有化,已达到数据和操作信息隐蔽,有利于数据安全,防止无关人员修改。

    b)面向对象的继承:是为了软件重用,简单理解就是代码复用,把重复使用的代码精简掉的一种手段。至于如何精简,当一个类中已经有了相应的属性和操作的代码,而另一个类当中也需要写重复的代码,那么就用继承方法,把前面的类当成父类,后面的类当成子类,子类继承父类。用一个关键字extends就完成了代码的复用。

    c)多态:没有继承就没有多态,继承是多态的前提。虽然继承自同一父类,但是相应的操作却各不相同,这叫多态。由继承而产生的不同的派生类,其对象对同一消息会做出不同的响应。

    测试程序2:

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

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

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

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

     程序5-4如下:

     1 package abstractClasses;
     2 
     3 /**
     4  * This program demonstrates abstract classes.
     5  * @version 1.01 2004-02-21
     6  * @author Cay Horstmann
     7  */
     8 public class PersonTest
     9 {
    10    public static void main(String[] args)
    11    {
    12 //       抽象类的声明,但不能将抽象类实例化 ,实例化的是Person类的子类
    13 //      父类引用可以引用,子类对象,因为父类引用的方法不会超过子类对象的方法,但反之不行
    14       Person[] people = new Person[2];
    15 
    16       // 用学生和雇员填充人物数组
    17       people[0] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
    18       people[1] = new Student("Maria Morris", "computer science");
    19 
    20       // 打印所有人对象的名称和描述
    21       for (Person p : people)
    22          System.out.println(p.getName() + ", " + p.getDescription());
    23    }
    24 }

    student类

     1 package abstractClasses;
     2 
     3 public class Student extends Person
     4 {
     5    private String major;
     6 
     7    /**
     8     * @param nama the student's name
     9     * @param major the student's major
    10     */
    11    public Student(String name, String major)
    12    {
    13       // 通过n to 总纲构造函数
    14       super(name);
    15       this.major = major;
    16    }
    17 
    18    public String getDescription()
    19    {
    20       return "a student majoring in " + major;
    21    }
    22 }

    person类

     1 package abstractClasses;
     2 
     3 public abstract class Person
     4 {
     5      //包含一个或多个抽象方法的类被称为抽象类,由abstract关键字修饰
     6     //通用的作用域和方法也放到了这里,抽象类不能被实例化,但可以被声明
     7    public abstract String getDescription();
     8    private String name;
     9 
    10    public Person(String name)
    11    {
    12       this.name = name;
    13    }
    14 
    15    public String getName()
    16    {
    17       return name;
    18    }
    19 }

    employee类

     1 package abstractClasses;
     2 
     3 import java.time.*;
     4 
     5 public class Employee extends Person
     6 {
     7    private double salary;
     8    private LocalDate hireDay;
     9 
    10    public Employee(String name, double salary, int year, int month, int day)
    11    {
    12       super(name);
    13       this.salary = salary;
    14       hireDay = LocalDate.of(year, month, day);
    15    }
    16 
    17    public double getSalary()
    18    {
    19       return salary;
    20    }
    21 
    22    public LocalDate getHireDay()
    23    {
    24       return hireDay;
    25    }
    26 
    27  //重写父类方法,返回一个格式化的字符串
    28    public String getDescription()
    29    {
    30       return String.format("an employee with a salary of $%.2f", salary);
    31    }
    32 
    33    public void raiseSalary(double byPercent)
    34    {
    35       double raise = salary * byPercent / 100;
    36       salary += raise;
    37    }
    38 }

    程序运行结果如下:

    测试程序3:

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

    2)掌握Object类的定义及用法;

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

    程序5-8如下:

     1 package equals;
     2 
     3 /**
     4  * This program demonstrates the equals method.
     5  * @version 1.12 2012-01-26
     6  * @author Cay Horstmann
     7  */
     8 public class EqualsTest
     9 {
    10    public static void main(String[] args)
    11    {
    12       Employee alice1 = new Employee("Alice Adams", 75000, 1987, 12, 15);
    13       Employee alice2 = alice1;
    14       Employee alice3 = new Employee("Alice Adams", 75000, 1987, 12, 15);
    15       Employee bob = new Employee("Bob Brandson", 50000, 1989, 10, 1);
    16 
    17       System.out.println("alice1 == alice2: " + (alice1 == alice2));
    18 
    19       System.out.println("alice1 == alice3: " + (alice1 == alice3));
    20 
    21       System.out.println("alice1.equals(alice3): " + alice1.equals(alice3));
    22 
    23       System.out.println("alice1.equals(bob): " + alice1.equals(bob));
    24 
    25       System.out.println("bob.toString(): " + bob);
    26 
    27       Manager carl = new Manager("Carl Cracker", 80000, 1987, 12, 15);
    28       Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15);
    29       boss.setBonus(5000);
    30       System.out.println("boss.toString(): " + boss);
    31       System.out.println("carl.equals(boss): " + carl.equals(boss));
    32       System.out.println("alice1.hashCode(): " + alice1.hashCode());
    33       System.out.println("alice3.hashCode(): " + alice3.hashCode());
    34       System.out.println("bob.hashCode(): " + bob.hashCode());
    35       System.out.println("carl.hashCode(): " + carl.hashCode());
    36    }
    37 }

     Manager类

     1 package equals;
     2 
     3 public class Manager extends Employee
     4 {
     5    private double bonus;
     6 
     7    public Manager(String name, double salary, int year, int month, int day)
     8    {
     9       super(name, salary, year, month, day);
    10       bonus = 0;
    11    }
    12 
    13    public double getSalary()
    14    {
    15       double baseSalary = super.getSalary();
    16       return baseSalary + bonus;
    17    }
    18 
    19    public void setBonus(double bonus)
    20    {
    21       this.bonus = bonus;
    22    }
    23 
    24    public boolean equals(Object otherObject)
    25    {
    26       if (!super.equals(otherObject)) return false;
    27       Manager other = (Manager) otherObject;
    28       // 检查这个和其他属于同一个类
    29       return bonus == other.bonus;
    30    }
    31 
    32    public int hashCode()
    33    {
    34       return java.util.Objects.hash(super.hashCode(), bonus);
    35    }
    36 
    37    public String toString()
    38    {
    39       return super.toString() + "[bonus=" + bonus + "]";
    40    }
    41 }

    employee类

     1 package equals;
     2 
     3 import java.time.*;
     4 import java.util.Objects;
     5 
     6 public class Employee
     7 {
     8    private String name;
     9    private double salary;
    10    private LocalDate hireDay;
    11 
    12    public Employee(String name, double salary, int year, int month, int day)
    13    {
    14       this.name = name;
    15       this.salary = salary;
    16       hireDay = LocalDate.of(year, month, day);
    17    }
    18 
    19    public String getName()
    20    {
    21       return name;
    22    }
    23 
    24    public double getSalary()
    25    {
    26       return salary;
    27    }
    28 
    29    public LocalDate getHireDay()
    30    {
    31       return hireDay;
    32    }
    33 
    34    public void raiseSalary(double byPercent)
    35    {
    36       double raise = salary * byPercent / 100;
    37       salary += raise;
    38    }
    39 
    40    public boolean equals(Object otherObject)
    41    {
    42       // 快速检查对象是否相同
    43 //       这里获得一个对象参数,第一个if语句判断两个引用是否是同一个,如果是那么这两个对象肯定相等
    44       if (this == otherObject) return true;
    45 
    46       // 如果显式参数为空,则必须返回false
    47       if (otherObject == null) return false;
    48 
    49 //      getClass()方法是得到对象的类,这里就是如果两个对象的类不一样,那么就不相等
    50       if (getClass() != otherObject.getClass()) return false;
    51 
    52       // 现在我们知道另一个对象是非空雇员
    53 //      在以上判断完成,再将得到的参数对象强制转换为该对象,考虑到父类引用子类的对象的出现,然后再判断对象的属性是否相同
    54       Employee other = (Employee) otherObject;
    55 
    56       // 测试字段是否具有相同的值
    57       return Objects.equals(name, other.name) && salary == other.salary && Objects.equals(hireDay, other.hireDay);
    58    }
    59 
    60    public int hashCode()
    61 //   哈希散列
    62    {
    63       return Objects.hash(name, salary, hireDay); 
    64    }
    65 // toString()方法,可自动生成
    66    public String toString()
    67    {
    68       return getClass().getName() + "[name=" + name + ",salary=" + salary + ",hireDay=" + hireDay
    69             + "]";
    70    }
    71 }

    程序运行结果:

    测试程序4:

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

    2)掌握ArrayList类的定义及用法;

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

    程序5-11如下:

     1 package arrayList;
     2 
     3 import java.util.*;
     4 
     5 /**
     6  * This program demonstrates the ArrayList class.
     7  * @version 1.11 2012-01-26
     8  * @author Cay Horstmann
     9  */
    10 public class ArrayListTest
    11 {
    12    public static void main(String[] args)
    13    {
    14       // 用三个雇员对象填充工作人员数组列表
    15       ArrayList<Employee> staff = new ArrayList<>();
    16 
    17       staff.add(new Employee("Carl Cracker", 75000, 1987, 12, 15));
    18       staff.add(new Employee("Harry Hacker", 50000, 1989, 10, 1));
    19       staff.add(new Employee("Tony Tester", 40000, 1990, 3, 15));
    20 
    21       // 把每个人的薪水提高5%
    22       for (Employee e : staff)
    23          e.raiseSalary(5);
    24 
    25       // 打印所有员工对象的信息
    26       for (Employee e : staff)
    27          System.out.println("name=" + e.getName() + ",salary=" + e.getSalary() + ",hireDay="
    28                + e.getHireDay());
    29    }
    30 }

    employee类

     1 package arrayList;
     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 }

    程序运行结果:

    测试程序5:

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

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

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

    程序5-12如下:

     1 package enums;
     2 
     3 import java.util.*;
     4 
     5 /**
     6  * This program demonstrates enumerated types.
     7  * @version 1.0 2004-05-24
     8  * @author Cay Horstmann
     9  */
    10 public class EnumTest
    11 {  
    12    public static void main(String[] args)
    13    {  
    14       Scanner in = new Scanner(System.in);
    15       System.out.print("Enter a size: (SMALL, MEDIUM, LARGE, EXTRA_LARGE) ");
    16       String input = in.next().toUpperCase();
    17       Size size = Enum.valueOf(Size.class, input);
    18       System.out.println("size=" + size);
    19       System.out.println("abbreviation=" + size.getAbbreviation());
    20       if (size == Size.EXTRA_LARGE)
    21          System.out.println("Good job--you paid attention to the _.");      
    22    }
    23 }
    24 
    25 enum Size
    26 {
    27    SMALL("S"), MEDIUM("M"), LARGE("L"), EXTRA_LARGE("XL");
    28 
    29    private Size(String abbreviation) { this.abbreviation = abbreviation; }
    30    public String getAbbreviation() { return abbreviation; }
    31 
    32    private String abbreviation;
    33 }

    程序运行结果:

    实验2:编程练习1

    1)定义抽象类Shape:

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

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

    2)让Rectangle与Circle继承自Shape类。

    3)编写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

    实验代码如下:

     1 package shape;
     2 
     3 import java.math.*;
     4 import java.util.*;
     5 import shape.shape;
     6 import shape.Rectangle;
     7 import shape.Circle;
     8 
     9 public class shapecount 
    10 {
    11 
    12     public static void main(String[] args) 
    13     {
    14         Scanner in = new Scanner(System.in);
    15         String rect = "rect";
    16         String cir = "cir";
    17         System.out.print("请输入形状个数:");
    18         int n = in.nextInt();
    19         shape[] score = new shape[n];
    20         for(int i=0;i<n;i++)
    21         {
    22             System.out.println("请输入形状类型 (rect or cir):");
    23             String input = in.next();
    24             if(input.equals(rect))
    25             {
    26                 double length = in.nextDouble();
    27                 double width = in.nextDouble();
    28                 System.out.println("Rectangle["+"length:"+length+"  "+width+"]");
    29                 score[i] = new Rectangle(width,length);
    30             }
    31             if(input.equals(cir)) 
    32             {
    33                 double radius = in.nextDouble();
    34                 System.out.println("Circle["+"radius:"+radius+"]");
    35                 score[i] = new Circle(radius);
    36             }
    37         }
    38         shapecount c = new shapecount();
    39         System.out.println(c.sumAllPerimeter(score));
    40         System.out.println(c.sumAllArea(score));
    41         for(shape s:score) 
    42         {
    43 
    44             System.out.println(s.getClass()+",  "+s.getClass().getSuperclass());
    45         }
    46     }
    47 
    48     public double sumAllArea(shape score[])
    49     {
    50          double sum = 0;
    51          for(int i = 0;i<score.length;i++)
    52              sum+= score[i].getArea();
    53          return sum;
    54     }
    55     
    56     public double sumAllPerimeter(shape score[])
    57     {
    58          double sum = 0;
    59          for(int i = 0;i<score.length;i++)
    60              sum+= score[i].getPerimeter();
    61          return sum;
    62     }
    63     
    64 }
    1 package shape;
    2 
    3 public abstract class shape
    4 {
    5     double PI = 3.14;
    6     public abstract double  getPerimeter();
    7     public abstract double  getArea();
    8 }
     1 package shape;
     2 
     3 public class Rectangle extends shape
     4 {
     5     private double width;
     6     private double length;
     7     public Rectangle(double w,double l)
     8     {
     9         this.width = w;
    10         this.length = l;
    11     }
    12     public double getPerimeter()
    13     {
    14         double Perimeter = (width+length)*2;
    15         return Perimeter;
    16     }
    17     public double getArea()
    18     {
    19         double Area = width*length;
    20         return Area;
    21     }
          public String toString()
          {
              return getClass().getName() + "[ width=" +  width + "]"+ "[length=" + length + "]";
          }
    22 }
     1 package shape;
     2 
     3 public class Circle extends shape
     4 {
     5 
     6     private double radius;
     7     public Circle(double r)
     8     {
     9         radius = r;
    10     }
    11     public double getPerimeter()
    12     {
    13         double Perimeter = 2*PI*radius;
    14         return Perimeter;
    15     }
    16     public double getArea()
    17     {
    18         double Area = PI*radius*radius;
    19         return Area;
    20     }
    21     public String toString()
    {
              return  getClass().getName() + "[radius=" + radius + "]";
    22    }  
    23 }

     程序运行结果如下:

    实验3:编程练习2

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

    实验代码如下:

      1 package IDcard;
      2 
      3 import java.io.BufferedReader;
      4 import java.io.File;
      5 import java.io.FileInputStream;
      6 import java.io.FileNotFoundException;
      7 import java.io.IOException;
      8 import java.io.InputStreamReader;
      9 import java.util.ArrayList;
     10 import java.util.Scanner;
     11 
     12 public class ID {
     13 
     14     public static People findPeopleByname(String name) {
     15         People flag = null;
     16         for (People people : peoplelist) {
     17             if(people.getName().equals(name)) {
     18                 flag = people;
     19             }
     20         }
     21         return flag;
     22 
     23     }
     24 
     25     public static People findPeopleByid(String id) {
     26         People flag = null;
     27         for (People people : peoplelist) {
     28             if(people.getnumber().equals(id)) {
     29                 flag = people;
     30             }
     31         }
     32         return flag;
     33 
     34     }
     35        
     36     private static ArrayList<People> peoplelist; 
     37     
     38     public static void main(String[] args) {
     39         peoplelist = new ArrayList<People>();
     40         Scanner scanner = new Scanner(System.in);
     41         File file = new File("D:\身份证号.txt");
     42         try {
     43             FileInputStream files = new FileInputStream(file);
     44             BufferedReader in = new BufferedReader(new InputStreamReader(files));
     45             String temp = null;
     46             while ((temp = in.readLine()) != null) {
     47                 
     48                 Scanner linescanner = new Scanner(temp);
     49                 linescanner.useDelimiter(" ");    
     50                 String name = linescanner.next();
     51                 String number = linescanner.next();
     52                 String sex = linescanner.next();
     53                 String age = linescanner.next();
     54                 String place = linescanner.nextLine();
     55                 People people = new People();
     56                 people.setName(name);
     57                 people.setnumber(number);
     58                 people.setage(age);
     59                 people.setsex(sex);
     60                 people.setplace(place);
     61                 peoplelist.add(people);
     62 
     63             }
     64         } catch (FileNotFoundException e) {
     65             System.out.println("文件未找到");
     66             e.printStackTrace();
     67         } catch (IOException e) {
     68             System.out.println("文件读取错误");
     69             e.printStackTrace();
     70         }
     71         boolean isTrue = true;
     72         while (isTrue) {
     73 
     74             System.out.println("***********");
     75             System.out.println("1.按姓名查询");
     76             System.out.println("2.按身份证号查询");
     77             System.out.println("3.退出");
     78             System.out.println("***********");
     79             int nextInt = scanner.nextInt();
     80             switch (nextInt) {
     81             case 1:
     82                 System.out.println("请输入姓名:");
     83                 String peoplename = scanner.next();
     84                 People people = findPeopleByname(peoplename);
     85                 if (people != null) {
     86                     System.out.println("   姓名:"+ people.getName() +
     87                                        "  身份证号:"+ people.getnumber() +
     88                                        "   年龄:"+ people.getage()+
     89                                        "   性别:"+ people.getsex()+
     90                                        "   地址:"+ people.getplace()
     91                             );
     92                 } else {
     93                     System.out.println("不存在此人");
     94                 }
     95                 break;
     96             case 2:
     97                 System.out.println("请输入身份证号:");
     98                 String peopleid = scanner.next();
     99                 People people1 = findPeopleByid(peopleid);
    100                 if (people1 != null) {
    101                     System.out.println("   姓名:"+ people1.getName()+
    102                                        "  身份证号:"+ people1.getnumber()+
    103                                        "   年龄:"+ people1.getage()+
    104                                        "   性别:"+ people1.getsex()+
    105                                        "   地址:"+ people1.getplace());
    106                 } else {
    107                     System.out.println("不存在此人");
    108                 }
    109                 break;
    110             case 3:
    111                 isTrue = false;
    112                 System.out.println("byebye!");
    113                 break;
    114             default:
    115                 System.out.println("输入有误");
    116             }
    117         }
    118     }
    119 
    120 
    121 }
     1 package IDcard;
     2 
     3 public class People {
     4 
     5     private    String name;
     6     private    String number;
     7     private    String age;
     8     private    String sex;
     9     private    String place;
    10 
    11     public String getName()
    12     {
    13         return name;
    14     }
    15     public void setName(String name) 
    16     {
    17         this.name = name;
    18     }
    19     public String getnumber() 
    20     {
    21         return number;
    22     }
    23     public void setnumber(String number)
    24     {
    25         this.number = number;
    26     }
    27     public String getage() 
    28     {
    29         return age;
    30     }
    31     public void setage(String age ) 
    32     {
    33         this.age = age;
    34     }
    35     public String getsex() 
    36     {
    37         return sex;
    38     }
    39     public void setsex(String sex ) 
    40     {
    41         this.sex = sex;
    42     }
    43     public String getplace() 
    44     {
    45         return place;
    46     }
    47     public void setplace(String place) 
    48     {
    49         this.place = place;
    50     }
    51 }

    运行结果如下:

     第三部分:总结

      在老师上课梳理脉络的前提下,我通过这周的自主学习,掌握了关于继承的相关知识和实验技能。这周因为国庆假期的时间很充足,所以在这个假期我很好的将以前所学知识和第五、六周所学结合起来,融会贯通。一步一步完成了学习任务。实验并没有太大的的问题,但是在完成老师布置的自主实验时,因为身体原因,写程序的时候思维逻辑并不是很清晰,所以程序代码可能有点凌乱,不过还是完成了题目要求的内容。通过这一个多月Java的学习,自己对程序语言又有了更深的理解,每次试验后,自己的反思和老师的点评,还有学长和同窗的指教都给了我很大的提升。而且通过老师的这种学习模式更好的培养了我们最欠缺的自主学习能力。很大程度上提升了我们的可塑性和可持续发展性。

  • 相关阅读:
    【HNOI2015】落忆枫音
    【HNOI2015】菜肴制作
    【HNOI2015】亚瑟王
    php内置函数分析之strrev()
    php内置函数分析之ucwords()
    php内置函数分析之strtoupper()、strtolower()
    php内置函数分析之ucfirst()、lcfirst()
    php内置函数分析之trim()
    nginx安装配置目录
    nginx 正向代理
  • 原文地址:https://www.cnblogs.com/hackerZT-7/p/9725225.html
Copyright © 2011-2022 走看看