前面题目形状中我们看到,为了输出所有形状的周长与面积,需要建立多个数组进行多次循环。这次试验使用继承与多态来改进我们的设计。
1.定义抽象类Shape
属性:不可变静态常量double PI
,值为3.14
,
抽象方法:public double getPerimeter()
,public double getArea()
2.Rectangle与Circle类均继承自Shape类。
Rectangle类(属性:int width,length)、Circle类(属性:int radius)。
带参构造方法为Rectangle(int width,int length)
,Circle(int radius)
。toString
方法(Eclipse自动生成)
3.编写double sumAllArea
方法计算并返回传入的形状数组中所有对象的面积和与double sumAllPerimeter
方法计算并返回传入的形状数组中所有对象的周长和。
4.main方法
4.1 输入整型值n,然后建立n个不同的形状。如果输入rect,则依次输入宽、长。如果输入cir,则输入半径。
4.2 然后输出所有的形状的周长之和,面积之和。并将所有的形状信息以样例的格式输出。 提示:使用Arrays.toString
。
4.3 最后输出每个形状的类型与父类型.使用类似shape.getClass()
//获得类型, shape.getClass().getSuperclass()
//获得父类型;
注意:处理输入的时候使用混合使用nextInt
与nextLine
需注意行尾回车换行问题。
4
rect
3 1
rect
1 5
cir
1
cir
2
38.84
23.700000000000003
[Rectangle [width=3, length=1], Rectangle [width=1, length=5], Circle [radius=1], Circle [radius=2]]
class Rectangle,class Shape
class Rectangle,class Shape
class Circle,class Shape
class Circle,class Shape
import java.util.*;
public class Main {
public static double sumAllArea(double areaall)
{
return areaall;
}
public static double sumAllPerimeter(double perimeterall)
{
return perimeterall;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.nextLine();
Shape []xz = new Shape[n];
double sumAllArea = 0, sumAllPerimeter = 0;
for(int i = 0;i < n;i++)
{
String ss = sc.nextLine();
if(ss.equals("rect"))
{
int a = sc.nextInt(),b = sc.nextInt();
sc.nextLine();
xz[i] = new Rectangle(a,b);
}
if(ss.equals("cir"))
{
int r = sc.nextInt();
sc.nextLine();
xz[i] = new Circle(r);
}
sumAllArea += xz[i].getArea();
sumAllPerimeter += xz[i].getPerimeter();
}
System.out.println(sumAllPerimeter(sumAllPerimeter));
System.out.println(sumAllArea(sumAllArea));
System.out.print("[");
for(int i = 0;i < n;i++)
{
if(i != 0)
System.out.print(", ");
System.out.print(xz[i].toString());
}
System.out.println("]");
for(int i = 0;i < n;i++)
{
System.out.println(xz[i].getClass()+","+xz[i].getClass().getSuperclass());
}
sc.close();
}
}
abstract class Shape {
final double PI = 3.14;
public abstract double getPerimeter();
public abstract double getArea();
}
class Rectangle extends Shape {
public int width;
public int length;
public Rectangle(int width, int length) {
super();
this.width = width;
this.length = length;
}
@Override
public String toString() {
return "Rectangle [width=" + width + ", length=" + length + "]";
}
public double getPerimeter() {
return 2*(width+length);
}
public double getArea() {
return width*length;
}
}
class Circle extends Shape {
public int radius;
public Circle(int radius) {
super();
this.radius = radius;
}
@Override
public String toString() {
return "Circle [radius=" + radius + "]";
}
public double getPerimeter() {
return 2*PI*radius;
}
public double getArea() {
return PI*radius*radius;
}
}
Java每个对象都继承自Object,都有equals、toString等方法。
现在需要定义PersonOverride
类并覆盖其toString
与equals
方法。
a. 属性:String name
、int age
、boolean gender
,所有的变量必须为私有(private)。
b. 有参构造方法,参数为name, age, gender
c. 无参构造方法,使用this(name, age,gender)
调用有参构造函数。参数值分别为"default",1,true
d.toString()
方法返回格式为:name-age-gender
e. equals
方法需比较name、age、gender,这三者内容都相同,才返回true
.
2.1 输入n1,使用无参构造函数创建n1个对象,放入数组persons1。
2.2 输入n2,然后指定name age gender
。每创建一个对象都使用equals方法比较该对象是否已经在数组中存在,如果不存在,才将该对象放入数组persons2。
2.3 输出persons1数组中的所有对象
2.4 输出persons2数组中的所有对象
2.5 输出persons2中实际包含的对象的数量
2.5 使用System.out.println(Arrays.toString(PersonOverride.class.getConstructors()));
输出PersonOverride的所有构造函数。
提示:使用ArrayList
代替数组大幅复简化代码,请尝试重构你的代码。
1
3
zhang 10 true
zhang 10 true
zhang 10 false
default-1-true
zhang-10-true
zhang-10-false
2
[public PersonOverride(), public PersonOverride(java.lang.String,int,boolean)]
import java.util.Arrays;
import java.util.Objects;
import java.util.Scanner;
class PersonOverride{
private String name;
private int age;
private boolean gender;
@Override
public String toString() {
return name + "-" + age + "-" + gender;
}
@Override
public boolean equals(Object obj){
if (this == obj){
return true;
}
if(obj == null)
{
return false;
}
if (this.getClass() != obj.getClass()){
return false;
}
PersonOverride p = (PersonOverride)obj;
boolean b1 = Objects.equals((this.name), p.name);
boolean b2 = (this.age == p.age);
boolean b3 = (this.gender == p.gender);
if(b1 && b2 && b3){
return true;
}
return false;
}
public PersonOverride(String _name, int _age, boolean _gender){
name = _name;
age = _age;
gender = _gender;
}
public PersonOverride(){
this("default",1,true);
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n1 = scanner.nextInt();
PersonOverride[] persons1 = new PersonOverride[n1];
for (int i = 0; i < n1; i++) {
persons1[i] = new PersonOverride();
}
int n2 = scanner.nextInt();
scanner.nextLine();
PersonOverride[] persons2 = new PersonOverride[n2];
for (int i = 0; i < n2; i++) {
String str = scanner.nextLine();
String[] arr = str.split("\\s+");
PersonOverride temp = new PersonOverride(arr[0],Integer.parseInt(arr[1]),Boolean.valueOf(arr[2]));
boolean flag = true;
for (int j = 0; j < n2; j++) {
if(temp.equals(persons2[j])){
flag = false;
}
}
if(flag){
persons2[i] = new PersonOverride(arr[0],Integer.parseInt(arr[1]),Boolean.valueOf(arr[2]));
}
}
for (int i = 0; i < n1; i++) {
System.out.println(persons1[i]);
}
int i,count = 0;
for (i = 0; i < n2; i++) {
if(persons2[i] == null){
continue;
}
count++;
System.out.println(persons2[i]);
}
System.out.println(count);
System.out.println(Arrays.toString(PersonOverride.class.getConstructors()));
}
}
Arrays.sort可以对所有实现Comparable的对象进行排序。但如果有多种排序需求,如有时候需对name进行降序排序,有时候只需要对年龄进行排序。使用Comparable无法满足这样的需求。可以编写不同的Comparator
来满足多样的排序需求。
属性:private name(String)
、private age(int)
有参构造函数:参数为name,age
toString方法:返回格式name-age
NameComparator
类,实现对name进行升序排序AgeComparator
类,对age进行升序排序System.out.println(Arrays.toString(NameComparator.class.getInterfaces()));
System.out.println(Arrays.toString(AgeComparator.class.getInterfaces()));
5
zhang 15
zhang 12
wang 14
Wang 17
li 17
NameComparator:sort
Wang-17
li-17
wang-14
zhang-15
zhang-12
AgeComparator:sort
zhang-12
wang-14
zhang-15
Wang-17
li-17
//最后两行是标识信息
import java.util.*;
class PersonSortable2{
private String name;
private int age;
PersonSortable2(String name , int age){
this.age = age;
this.name = name;
}
public String getName() {
return name;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public String toString(){
return this.getName() + "-" + this.getAge();
}
}
class NameComparator implements Comparator{
@Override
public int compare(Object o1 , Object o2) {
return ((PersonSortable2)o1).getName().compareTo(((PersonSortable2)o2).getName());
}
}
class AgeComparator implements Comparator{
@Override
public int compare(Object o1 , Object o2) {
return ((PersonSortable2)o1).getAge() - ((PersonSortable2)o2).getAge();
}
}
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
Object []O = new Object[n];
for(int i = 0 ; i < n ; i ++){
O[i] = new PersonSortable2(scan.next() , scan.nextInt());
}
Arrays.sort(O , new NameComparator());
System.out.println("NameComparator:sort");
for(Object o : O){
System.out.println(o);
}
Arrays.sort(O , new AgeComparator());
System.out.println("AgeComparator:sort");
for(Object o : O){
System.out.println(o);
}
System.out.println(Arrays.toString(NameComparator.class.getInterfaces()));
System.out.println(Arrays.toString(AgeComparator.class.getInterfaces()));
}
}
定义Person抽象类,Student类、Company类,Employee类。
Person类的属性:String name, int age, boolean gender
Person类的方法:
public Person(String name, int age, boolean gender);
public String toString(); //返回"name-age-gender"格式的字符串
public boolean equals(Object obj);//比较name、age、gender,都相同返回true,否则返回false
Student类继承自Person
,属性:String stuNo, String clazz
Student类的方法:
//建议使用super复用Person类的相关有参构造函数
public Student(String name, int age, boolean gender, String stuNo, String clazz);
public String toString(); //返回 “Student:person的toString-stuNo-clazz”格式的字符串
public boolean equals(Object obj);//首先调用父类的equals方法,如果返回true,则继续比较stuNo与clazz。
Company类属性:String name
Company类方法:
public Company(String name);
public String toString(); //直接返回name
public boolean equals(Object obj);//name相同返回true
Employee类继承自Person
,属性:Company company, double salary
Employee类方法:
//建议使用super复用Person类的相关有参构造函数
public Employee(String name, int age, boolean gender, double salary, Company company);
public String toString(); //返回"Employee:person的toString-company-salary"格式的字符串
public boolean equals(Object obj);//首先调用父类的equals方法,如果返回true。再比较company与salary。
//比较salary属性时,使用DecimalFormat df = new DecimalFormat("#.#");保留1位小数
编写equals方法重要说明:
null
的情况。如果company不为null且传入为null,返回falsenull
情况。提示
s
,然后依次输入name age gender stuNo clazz
创建Student对象。e
,然后依次输入name age gender salary company
创建Employee对象。List personList
。输入其他字符,则结束创建。创建说明: 对于String类型,如果为null
则不创建对象,而赋值为null
。对于company属性,如果为null则赋值为null
,否则创建相应的Company对象。
对personList中的元素实现先按照姓名升序排序,姓名相同再按照年龄升序排序。提示:可使用Comparable
或Comparator
接受输入,如果输入为exit
则return
退出程序,否则继续下面步骤。
将personList中的元素按照类型分别放到stuList与empList。注意:不要将两个内容相同的对象放入列表(是否相同是根据equals返回结果进行判定)。
输出字符串stuList
,然后输出stuList中的每个对象。
输出字符串empList
,然后输出empList中的每个对象。
1-3
为一个测试点 4-6
为一个测试点
s zhang 23 false 001 net15
e wang 18 true 3000.51 IBM
s zhang 23 false 001 net15
e bo 25 true 5000.51 IBM
e bo 25 true 5000.52 IBM
e bo 18 true 5000.54 IBM
e tan 25 true 5000.56 IBM
e tan 25 true 5000.51 IBM
s wang 17 false 002 null
s wang 17 false 002 null
e hua 16 false 1000 null
s wang 17 false 002 net16
e hua 16 false 1000 null
e hua 18 false 1234 MicroSoft
!
continue
Employee:bo-18-true-IBM-5000.54
Employee:bo-25-true-IBM-5000.51
Employee:bo-25-true-IBM-5000.52
Employee:hua-16-false-null-1000.0
Employee:hua-16-false-null-1000.0
Employee:hua-18-false-MicroSoft-1234.0
Employee:tan-25-true-IBM-5000.56
Employee:tan-25-true-IBM-5000.51
Student:wang-17-false-002-null
Student:wang-17-false-002-null
Student:wang-17-false-002-net16
Employee:wang-18-true-IBM-3000.51
Student:zhang-23-false-001-net15
Student:zhang-23-false-001-net15
stuList
Student:wang-17-false-002-null
Student:wang-17-false-002-net16
Student:zhang-23-false-001-net15
empList
Employee:bo-18-true-IBM-5000.54
Employee:bo-25-true-IBM-5000.51
Employee:hua-16-false-null-1000.0
Employee:hua-18-false-MicroSoft-1234.0
Employee:tan-25-true-IBM-5000.56
Employee:tan-25-true-IBM-5000.51
Employee:wang-18-true-IBM-3000.51
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Scanner;
abstract class Person{
private String name, c;
private int age;
private boolean gender;
public String getName() {
return name;
}
public String getC() {
return c;
}
public int getAge() {
return age;
}
public boolean isGender() {
return gender;
}
public Person(String c, String name, int age, boolean gender) {
this.c = c;
this.name = name;
this.age = age;
this.gender = gender;
}
@Override
public String toString() {
return name + "-" + age + "-" + gender;
}
@Override
public boolean equals(Object obj) {
Person per = (Person) obj;
if(per.name == null || this.name == null) {
return false;
}
return (per.name.compareTo(this.name) == 0 && per.age == this.age && per.gender == this.gender );
}
}
class Student extends Person{
private String stuNo;
private String clazz;
public Student(String c, String name, int age, boolean gender, String stuNo, String clazz) {
super(c, name, age, gender);
this.stuNo = stuNo;
this.clazz = clazz;
}
@Override
public String toString(){
return super.toString() + "-" + stuNo + "-" + clazz;
}
@Override
public boolean equals(Object obj) {
Student per = (Student)obj;
if(super.equals(obj)) {
if(per.stuNo == null || per.clazz == null || this.stuNo == null || this.clazz == null) {
return false;
}
return (per.stuNo.compareTo(this.stuNo) == 0 && per.clazz.compareTo(this.clazz) == 0);
}
return false;
}
}
class Company{
private String name;
public Company(String name) {
this.name = name;
}
@Override
public String toString() { //直接返回name
return name;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Company other = (Company) obj;
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
return true;
}
}
class Employee extends Person{
private Company company;
private double salary;
public Employee(String c, String name, int age, boolean gender, double salary, Company company) {
super(c, name, age, gender);
this.salary = salary;
this.company = company;
}
@Override
public String toString() {
return super.toString() + "-" + company.toString() + "-" + salary;
}
@Override
public boolean equals(Object obj) {
if(super.equals(obj)) {
Employee per = (Employee)obj;
if(this.company.toString() == null || per.company.toString() == null) {
return false;
}
String newpersalary = new DecimalFormat("#.#").format(per.salary);
String newthissalary = new DecimalFormat("#.#").format(this.salary);
return (per.company.toString().compareTo(this.company.toString()) == 0 && newpersalary.compareTo(newthissalary) == 0);
}
return false;
}
}
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
String c, name, stuNo, clazz, companyname, str;
int age;
boolean gender;
double salary;
ArrayList personList = new ArrayList();
ArrayList studentList = new ArrayList();
ArrayList employeeList = new ArrayList();
while(true) {
c = input.next();
if(c.compareTo("s") == 0) {
name = input.next();
age = input.nextInt();
gender = input.nextBoolean();
stuNo = input.next();
clazz = input.next();
Student student = new Student(c, name, age, gender, stuNo, clazz);
personList.add(student);
}
else if(c.compareTo("e") == 0) {
name = input.next();
age = input.nextInt();
gender = input.nextBoolean();
salary = input.nextDouble();
companyname = input.next();
Company company = new Company(companyname);
Employee employee = new Employee(c, name, age, gender, salary, company);
personList.add(employee);
}
else {
personList.sort(Comparator.comparing(Person::getName).thenComparingInt(Person::getAge));
for(int i = 0; i < personList.size(); ++i) {
if(personList.get(i).getC().compareTo("s") == 0) {
System.out.println("Student:" + personList.get(i).toString());
int flag = 0;
for(int j = 0; j < studentList.size(); ++j) {
if(studentList.get(j).equals(personList.get(i))) {
flag = 1;
break;
}
}
if(flag == 0) {
studentList.add((Student)personList.get(i));
}
}
else if(personList.get(i).getC().compareTo("e") == 0){
System.out.println("Employee:" + personList.get(i).toString());
int flag = 0;
for(int j = 0; j < employeeList.size(); ++j) {
if(employeeList.get(j).equals(personList.get(i))) {
flag = 1;
break;
}
}
if(flag == 0) {
employeeList.add((Employee)personList.get(i));
}
}
}
str = input.next();
if(str.compareTo("exit") == 0 || str.compareTo("return") == 0) {
return;
}
System.out.println("stuList");
for(int i = 0; i < studentList.size(); ++i) {
System.out.println("Student:" + studentList.get(i).toString());
}
System.out.println("empList");
for(int i = 0; i < employeeList.size(); ++i) {
System.out.println("Employee:" + employeeList.get(i).toString());
}
}
}
}
}
定义IntegerStack
接口,用于声明一个存放Integer元素的栈的常见方法:
public Integer push(Integer item);
//如果item为null,则不入栈直接返回null。如果栈满,也返回null。如果插入成功,返回item。
public Integer pop(); //出栈,如果为空,则返回null。出栈时只移动栈顶指针,相应位置不置为null
public Integer peek(); //获得栈顶元素,如果为空,则返回null.
public boolean empty(); //如果为空返回true
public int size(); //返回栈中元素个数
定义IntegerStack的实现类ArrayIntegerStack
,内部使用数组实现。创建时,可指定内部数组大小。
如果IntegerStack接口的实现类内部使用ArrayList来存储元素,怎么实现?测试代码需要进行什么修改?
5
3
1 2 3
2
1
2
3
3,false,3
[1, 2, 3, null, null]
3
2
1,false,1
[1, 2, 3, null, null]
import java.util.*;
interface IntegerStack{
public Integer push(Integer item);
public Integer pop();
public Integer peek();
public boolean empty();
public int size();
}
class ArrayIntegerStack{
public Integer [] array;
private int len;
public ArrayIntegerStack(int n) {
this.array = new Integer[n];
len=0;
}
public Integer push(Integer item) {
if(item==null) {
return null;
}
if(len==this.array.length) {
return null;
}
array[len++]=item;
return item;
}
public Integer pop() {
if(len==0) {
return null;
}
len--;
return array[len];
}
public Integer peek() {
if(len==0) {
return null;
}
return array[len-1];
}
public boolean empty() {
if(len==0) {
return true;
}
else {
return false;
}
}
public int size() {
return len;
}
}
public class Main{
public static void main(String [] args){
Scanner in=new Scanner(System.in);
int n = in.nextInt();
ArrayIntegerStack stack = new ArrayIntegerStack(n);
int m = in.nextInt();
for(int i=0;i
程序填空题。根据题目要求完善下面的代码。请提交完整代码。 一个木块如果高度比宽度大,我们说它是竖着放的,否则我们说它是平放的。 读入一个木块的高度和宽度。如果它是平放的,则输出A,否则输出B。
import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner in = new Scanner(System.in); int height, width; char status; height = in.nextInt(); width = in.nextInt(); Board board = new Board(height, width); status = board.getStatus(); System.out.print(status); } } class Board{ int height, width; public Board(int height, int width){ this.height = height; this.width = width; } public char getStatus(){ if(height<=width){ return status(1); }else{ return status(1.0); } } public char status(double rate){ } public char status(int rate){ } }
输入在一行中给出2个绝对值不超过1000的正整数A和B。
在一行中输出一个字符A或者B。
50 50
结尾无空行
A
结尾无空行
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int height=in.nextInt();
int width= in.nextInt();
char status;
Board board = new Board(height, width);
status = board.getStatus();
System.out.print(status);
}
}
class Board{
int height, width;
public Board(int height, int width){
this.height = height;
this.width = width;
}
public char getStatus(){
if(height<=width){
return status(1);
}else{
return status(1.0);
}
}
public char status(double rate) {
return 'B';
}
public char status(int rate) {
return 'A';
}
}
程序填空题。请补充以下代码,完成题目要求。(注意:需要提交完整代码) 有一个团队由5个人组成。他们每个人给指导老师一个分数,去掉最高分,去掉最低分,剩下的3个分数的平均分就是该团队对指导老师的评分。
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int[] grade = new int[5]; for(int i=0; i输入格式:
在一行中给出5个不超过10的正整数(从小到大排列)。
输出格式:
输出集体评分,保留小数点后两位。
输入样例:
1 2 4 6 9
结尾无空行
输出样例:
4.00
结尾无空行
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int[] grade = new int[5]; for(int i=0; i
7-8 集体评分2 (5 分)
程序填空题。请补充以下代码,完成题目要求。(注意:需要提交完整代码) 有一个团队由5个人组成。他们每个人给指导老师一个分数,去掉最高分,去掉最低分,剩下的3个分数的平均分就是该团队对指导老师的评分。
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int[] grade = new int[5]; for(int i=0; i输入格式:
在一行中给出5个不超过10的正整数(从小到大排列)。
输出格式:
输出集体评分,保留小数点后两位。
输入样例:
1 2 4 6 9
结尾无空行
输出样例:
4.00
结尾无空行
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int[] grade = new int[5]; for(int i=0; i
7-9 程序改错题2 (5 分)
程序改错题。以下代码存在错误,请修改后提交。
public class Main { public static void main(String[] args) { Animal animal = new Dog(); animal.shout(); animal.run(); } } class Animal { void shout() { System.out.println("animal shout!"); } } class Dog extends Animal { void shout() { super.shout(); System.out.println("wangwang……"); } void run() { System.out.println("Dog is running"); } }输入格式:
输出格式:
输入样例:
无
结尾无空行
输出样例:
animal shout! wangwang…… Dog is running
结尾无空行
public class Main { public static void main(String[] args) { Dog animal = new Dog(); animal.shout(); animal.run(); } } class Animal { void shout() { System.out.println("animal shout!"); } } class Dog extends Animal { @Override void shout() { super.shout(); System.out.println("wangwang……"); } void run() { System.out.println("Dog is running"); } }
7-10 程序填空题3 (5 分)
参照输出样例补全以下程序,使程序输出结果与输出样例一致。
public class Main { public static void main(String[] args) { Son son = new Son(); son.method(); } } class Parent { Parent() { System.out.println("Parent's Constructor without parameter"); } Parent(boolean b) { System.out.println("Parent's Constructor with a boolean parameter"); } public void method() { System.out.println("Parent's method()"); } } class Son extends Parent { //补全本类定义 }输入格式:
无
输出格式:
无
输入样例:
结尾无空行
输出样例:
Parent's Constructor with a boolean parameter Son's Constructor without parameter Son's method() Parent's method()
结尾无空行
public class Main { public static void main(String[] args) { Son son = new Son(); son.method(); } } class Parent { Parent() { System.out.println("Parent's Constructor without parameter"); } Parent(boolean b) { System.out.println("Parent's Constructor with a boolean parameter"); } public void method() { System.out.println("Parent's method()"); } } class Son extends Parent { private static boolean b; Son() { super(b); System.out.println("Son's Constructor without parameter"); } public void method() { System.out.println("Son's method()"); System.out.println("Parent's method()"); } }