欢迎光临
我们一直在努力

sdut-Java面向对象-05 类和对象(函数题:12-22题)

6-12 创建一个直角三角形类实现IShape接口

创建一个直角三角形类(regular triangle)RTriangle类,实现下列接口IShape。两条直角边长作为RTriangle类的私有成员,类中包含参数为直角边的构造方法。

interface IShape {// 接口

public abstract double getArea(); // 抽象方法 求面积

public abstract double getPerimeter(); // 抽象方法 求周长

}

###直角三角形类的定义:

直角三角形类的构造函数原型如下:
RTriangle(double a, double b);

其中 a 和 b 都是直角三角形的两条直角边。

裁判测试程序样例:

import java.util.Scanner;
import java.text.DecimalFormat;

interface IShape {
public abstract double getArea();

public abstract double getPerimeter();
}

/*你写的代码将嵌入到这里*/

public class Main {
public static void main(String[] args) {
DecimalFormat d = new DecimalFormat("#.####");
Scanner input = new Scanner(System.in);
double a = input.nextDouble();
double b = input.nextDouble();
IShape r = new RTriangle(a, b);
System.out.println(d.format(r.getArea()));
System.out.println(d.format(r.getPerimeter()));
input.close();
}
}

输入样例:

3.1 4.2

输出样例:

6.51
12.5202

实现代码:

class RTriangle implements IShape{
private double a;
private double b;
RTriangle(double a, double b){
super();
this.a = a;
this.b = b;
}

@Override
public double getArea() {
return this.a * this.b / 2.0;
}

@Override
public double getPerimeter() {
return this.a + this.b + Math.sqrt(a * a + b * b);
}
}

6-13 矩形

设计一个表示矩形的类Rectangle,这个类用一个表示坐标点的类Point的对象来表达它的左上角坐标,用一个表示尺寸的类Dimension的对象来表示它的大小。
你的程序要严格按照所给的类和函数的声明来实现。

函数接口定义:

/**
* Represents a point in 2D, with x and y, like (x,y).
*/
class Point {
private int x;
private int y;

/**
* Creates a point with coordinate at (x,y)
* @param x the x coordinate
* @param y the y coordinate
*/
public Point(int x, int y) {

}

/* (non-Javadoc)
* @see java.lang.Object#toString()
* The generated string as: "(x,y)
*/
@Override
public String toString() {

}

/**
* Moves the point with dx and dy.
* @param dx the distance to be moved at x-axis
* @param dy the distance to be moved at y-axis
*/
public void move(int dx, int dy) {

}

/**
* Calculate the distance between this and p.
* @param p the other point.
* @return the distance between this and p.
*/
public double distance(Point p) {

}
}

/**
* A dimension in 2D, with width and height.
*/
class Dimension {
private int width;
private int height;

/**
* Creates a dimension with specified width and height.
* @param width the width of the dimension
* @param height the height of the dimension
*/
public Dimension(int width, int height) {

}

/* (non-Javadoc)
* @see java.lang.Object#toString()
* The generated string as: "width by height"
*/
@Override
public String toString() {

}

/**
* Resizes the dimension with scales at width and height.
* Although the scales are in double, the result should be integers as well.
* @param widthScale the scale at width
* @param heightScale the scale at height
*/
public void resize(double widthScale, double heightScale) {

}

/**
* Calculate the area of this dimension.
* @return the area of this dimension.
*/
public int area() {

}
}

/**
* Represents a rectangle, with a point at its top-left and a dimension.
*
*/
class Rectangle {
private Point topleft;
private Dimension size;

/**
* Creates a rectangle.
* @param topleft the coordinate of its top-left
* @param size the dimension of its size
*/
public Rectangle(Point topleft, Dimension size) {

}

/* (non-Javadoc)
* @see java.lang.Object#toString()
* The generated string as: "Rectangle at (x,y):width by height"
*/
public String toString() {

}

/**
* Moves the rectangle some distance.
* @param dx the distance to be moved at x-axis
* @param dy the distance to be moved at y-axis
*/
public void move(int dx, int dy) {

}

/**
* Resizes the rectangle at both width and height
* @param widthScale the scale at width
* @param heightScale the scale at height
*/
public void resize(double widthScale, double heightScale) {

}

/**
* Calculates the area of this rectangle.
* @return the area of this rectangle.
*/
public double area() {

}

/**
* Calculates the distance between this rectangle and r.
* @param r the other rectangle
* @return the distance between this rectangle and r.
*/
public double distance(Rectangle r) {

}
}

裁判测试程序样例:

public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x = in.nextInt();
int y = in.nextInt();
int width = in.nextInt();
int height = in.nextInt();
Rectangle r = new Rectangle(
new Point(x,y), new Dimension(width, height));
Rectangle r2 = new Rectangle(
new Point(x,y), new Dimension(width, height));
int dx = in.nextInt();
int dy = in.nextInt();
r.move(dx, dy);
double widthScale = in.nextDouble();
double heightScale = in.nextDouble();
r.resize(widthScale, heightScale);
System.out.println(r);
System.out.printf("%.2f\\n", r.area());
System.out.printf("%.2f\\n", r.distance(r2));
in.close();
}
}

/* 请在这里填写答案 */

输入样例:

0 0 100 100 20 20 2 2

输出样例:

Rectangle at (20,20):200 by 200
40000.00
28.28

实现代码:

/**
* 2D平面中带的点,有x和y坐标,如:(x,y)。
*/
class Point {
int x;
int y;

/**
* C创建一个坐标为(x,y)的点
* @param x x坐标
* @param y y坐标
*/
public Point(int x, int y) {
this.x = x;
this.y = y;
}

/*
* 生成的字符串为:(x,y)
*/
@Override
public String toString() {
return "("+x+","+y+")";
}

/**
* 用dx和dy移动点。
* @param dx 在x轴上移动的距离
* @param dy 在y轴上移动的距离
*/
public void move(int dx, int dy) {
this.x += dx;
this.y += dy;
}

/**
* @param p 另外一个点
* @return 计算这个点和p点之间的距离。
*/
public double distance(Point p) {
return Math.sqrt((this.x – p.x) * (this.x – p.x) + (this.y – p.y) * (this.y – p.y));
}
}

/**
* 二维尺寸,有宽度和高度。
*/
class Dimension {
int width;
int height;

/**
* 创建具有指定宽度和高度的Dimension。
* @param width——Dimension的宽度
* @param height——Dimension的高度
*/
public Dimension(int width, int height) {
this.width = width;
this.height = height;
}

/*
* 生成的字符串为:"width by height"
*/
@Override
public String toString() {
return this.width + " by " + this.height;
}

/**
* R按宽度和高度的比例调整尺寸。
* 虽然标度是双精度的,但结果应该是整数。
* @param widthScale 宽度比例尺
* @param heightScale 高度比例尺
*/
public void resize(double widthScale, double heightScale) {
this.width *= widthScale;
this.height *= heightScale;
}

/**
* @return 计算这个Dimension的面积.
*/
public int area() {
return width*height;
}
}

/**
* 表示一个矩形,在其左上角有一个点Point和一个维度Dimension.
*
*/
class Rectangle {
Point topleft;
Dimension size;

/**
* 创建一个矩形。
* @param topleft 左上角的坐标
* @param size 它的尺寸
*/
public Rectangle(Point topleft, Dimension size) {
this.topleft = topleft;
this.size = size;
}

/*
* 生成的字符串如下: "Rectangle at (x,y):width by height"
*/
public String toString() {
return "Rectangle at (" + topleft.x + "," + topleft.y + "):" + size.width + " by " + size.height;
}

/**
* 将矩形移动一段距离。
* @param dx 在x轴上移动的距离
* @param dy 在y轴上移动的距离
*/
public void move(int dx, int dy) {
topleft.move(dx, dy);
}

/**
* 调整矩形的宽度和高度
* @param widthScale 宽度比例尺
* @param heightScale 高度比例尺
*/
public void resize(double widthScale, double heightScale) {
size.resize(widthScale, heightScale);
}

/**
* @return 这个矩形的面积。
*/
public double area() {
return size.area();
}

/**
* 计算矩形左上角顶点与矩形r左上角点之间的距离。
* @param r 另一个矩形
* @return 这个矩形和r之间的距离。
*/
public double distance(Rectangle r) {
return this.topleft.distance(r.topleft);
}
}

6-14 jmu-Java-03面向对象基础-clone方法、标识接口、深拷贝

Object的clone方法可以帮助我们克隆对象。现在需编写一个类Car包含:

1.属性:

private String name;
private CarDriver driver;
private int[] scores;

2.无参构造函数

public Car() {
}

3.方法:

@Override
public String toString() {
return "Car [name=" + name + ", driver=" + driver + ", scores=" + Arrays.toString(scores) + "]";
}

setter/getter方法与clone方法。注意:clone方法需实现对象的深度克隆。

CarDriver为已经定义好的类,部分代码如下:

class CarDriver {
private String name;
public CarDriver() {}
//setter/getter
//toString
}

/* 请在这里填写答案,即Car类的完整代码 */

实现代码:

class Car implements Cloneable
{
private String name;
private CarDriver driver;
private int[] scores;
public Car() {
}
@Override
public String toString() {
return "Car [name=" + name + ", driver=" + driver + ", scores=" + Arrays.toString(scores) + "]";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public CarDriver getDriver() {
return driver;
}
public void setDriver(CarDriver driver) {
this.driver = driver;
}
public int[] getScores() {
return scores;
}
public void setScores(int[] scores) {
this.scores = scores;
}
@Override
protected Car clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
Car car = new Car();
CarDriver D = new CarDriver();
if(driver==null)
D=null;
else
D.setName(driver.getName());
car.setDriver(D);
String Nm;
if(name==null)
Nm=null;
else
Nm=name;
car.setName(Nm);
if(scores==null)
car.setScores(null);
else
{
int c[] = Arrays.copyOf(scores, scores.length);
car.setScores(c);
}
return car;
}
}

6-15 可排序的学生类

要求:根据Main类中main方法中的代码,设计满足要求的Student(学生)类:1)包含属性:int no(学号)、String name(姓名);2)满足Main类中main方法代码的说明要求。
Main类中main方法代码的说明:1)首先,从键盘接收形如“3 cuizhenyu 2 tiangang 1 dingchangqing 4 zhangfeng”的字符串,该字符串中包含了4个学生的学号和姓名(各学生以及学生的学号和姓名之间都用一个空格分隔,姓名中只包含英文字母),然后将该字符串内容中的前3个学生的学号及其姓名放到到Student数组stus中;2)将stus中的3个Student放入到HashSet stuSet中(注意:如果学生的学号相同,则认为是相同对象,不放入stuSet中);3)将第4个学生对象放入到stuSet中,如果第4个学生对象的学号与stuSet中已有学生对象的学号相同则不能放入。然后,打印出当前stuSet中学生对象的个数;4)用Arrays.sort方法对数组stus按照学生姓名的字母顺序排序(先比较首字母,首字母相同的比较第二个字母,以此类推),输出排序后的stus中3个学生对象的内容,每个学生对象的输出格式为“no=XX&name=YY”。

函数接口定义:

Student

裁判测试程序样例:

import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;

public class Main{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Student[] stus = new Student[3];

for(int i=0;i<3;i++){
int no = scan.nextInt();
String name = scan.next();
Student s = new Student(no,name);
stus[i] =s;
}
//将stus中的3个学生对象,放入到HashSet中
HashSet<Student> stuSet = new HashSet<Student>();
for(Student s: stus){
stuSet.add(s);
}
//要放入的第4个Student
Student fourth = new Student(scan.nextInt(),scan.next());
stuSet.add(fourth);//如果fourth的学号(no)与stuSet中的已有学生的no重复则无法放入
System.out.println(stuSet.size());

Arrays.sort(stus);//对stus中的3个原有对象,按照姓名首字符有小到大排序
for(int i=0;i<stus.length;i++){
System.out.println(stus[i]);//输出的格式为:no=XX&name=YY
}

scan.close();
}
}
/* 请在这里填写答案 */

输入样例:

3 cuizhenyu 2 tiangang 1 dingchangqing 4 zhangfeng

输出样例:

4
no=3&name=cuizhenyu
no=1&name=dingchangqing
no=2&name=tiangang

实现代码:

class Student implements Comparable<Student> {
private int no;
private String name;
public Student(int no, String name) {
this.no = no;
this.name = name;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

public String toString() {
return "no=" + no + "&name=" + name;
}

public int compareTo(Student o) {
if(this.name.compareTo(o.name)<0) {
return -1;
}
else if(this.name.compareTo(o.name)>0)return 1;
return 0;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + no;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (no != other.no)
return false;
return true;
}

}

6-16 Person类

构造Person类。包括姓名(name),性别(sex)和年龄(age)。提供所有属性的set和get函数,提供print函数打印其信息

输入描述:

姓名(name),性别(sex)和年龄(age)

输出描述:

用户信息

裁判测试程序样例:

import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String name = scan.next();
String sex = scan.next();
int age = scan.nextInt();
Person p = new Person();
p.setName(name);
p.setSex(sex);
p.setAge(age);
p.print();
scan.close();
}
}

/* 你的代码被嵌在这里 */

输入样例:

在这里给出一组输入。例如:

Lucy male 23

输出样例:

在这里给出相应的输出。例如:

name:Lucy; sex:male; age:23

实现代码:

class Person{
String name,sex;
int age;

public String getName() {
return name;
}

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

public String getSex() {
return sex;
}

public void setSex(String sex) {
this.sex = sex;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}
public void print(){
System.out.println("name:"+name+"; sex:"+sex+"; age:"+age);
}
}

6-17 汽车类

编写汽车类,其功能有启动(start),停止(stop),加速(speedup)和减速(slowDown),启动和停止可以改变汽车的状态(on/off),初始时状态为off,速度为0,speedUp和slowDown可以调整汽车的速度,每调用一次汽车速度改变10(加速增10,减速减10),汽车启动后才能加减速,加速上限为160,减速下限为0,汽车速度减为0后才能停止,给出汽车类的定义。
Main函数中构造一个汽车对象,并对该对象进行操作,各个操作的编号为:

  • start
  • stop
  • speedup
  • slowdown
    操作完成后打印出汽车的状态和速度。
  • 输入描述:

    操作

    输出描述:

    汽车的状态和速度

    裁判测试程序样例:

    import java.util.Scanner;
    public class Main{

    public static void main(String[] args) {
    Scanner s = new Scanner(System.in);
    int n = s.nextInt();
    Car c = new Car();
    for (int i=0;i<n;i++) {
    int a = s.nextInt();
    switch (a) {
    case 1: c.start(); break;
    case 2: c.stop(); break;
    case 3: c.speedUp(); break;
    case 4: c.slowDown(); break;
    }
    }
    System.out.print(c.status + " ");
    System.out.println(c.speed);
    }

    }

    /* 你的代码被嵌在这里 */

    输入样例:

    在这里给出一组输入。例如:

    8
    1 3 3 4 3 4 4 2

    输出样例:

    在这里给出相应的输出。例如:

    off 0

    实现代码:

    class Car{
    public int speed = 0;
    public String status = "off";
    public void start() {
    status="on";
    speed=0;
    }
    public void stop() {
    if(speed==0)
    status="off";
    }
    public void speedUp() {
    if(status=="on" && speed<160)
    speed+=10;
    }
    public void slowDown() {
    if(status=="on" && speed>0)
    speed-=10;
    }
    }

    6-18 家具类

    构建家具类Furniture,包括长、宽、高,均为整数(cm)。提供相应的构造函数和get、set函数。
    Main函数里构造家具对象,并调用相应的函数。

    输入描述:

    家具对象的长宽高

    输出描述:

    家具对象的相关属性

    裁判测试程序样例:

    import java.util.Scanner;

    public class Main {
    public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    Furniture f = new Furniture(sc.nextInt(),sc.nextInt(),sc.nextInt());
    System.out.println(f.getHeight());
    System.out.println(f.getLength());
    System.out.println(f.getWidth());
    }
    }

    /* 你的代码被嵌在这里*/

    输入样例:

    在这里给出一组输入。例如:

    50 60 100

    输出样例:

    在这里给出相应的输出。例如:

    100
    50
    60

    实现代码:

    class Furniture{
    int Height,Length,Width;
    public Furniture(int a,int b,int c){

    Length = a;
    Width = b;
    Height = c;
    }
    public int getHeight() {
    return Height;
    }

    public void setHeight(int height) {
    Height = height;
    }

    public int getLength() {
    return Length;
    }

    public void setLength(int length) {
    Length = length;
    }

    public int getWidth() {
    return Width;
    }

    public void setWidth(int width) {
    Width = width;
    }
    }

    6-19 sdust-Java-可实现多种排序的Book类

    设计Book类,要求:1)Book类的成员属性包括:书名name(String类型)、出版日期publishDate(Date类型)、定价price(double型);2)为Book对象提供按出版日期、价格排序的两种方式,且能够满足测试程序代码中的输入输出要求(注意代码注释中的说明)。其中,类BookComparatorByPrice的排序功能是:将一组Book对象按照价格升序排序,如果价格相同,则按照书名字母顺序排列;类BookComparatorByPubDate的排序功能是:将一组Book对象按照出版日期降序排序。

    裁判测试程序样例:

    public class Main {
    public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    Book[] books = new Book[4];
    //1. 从键盘接收用户输入的4本书的名称(仅有英文字符构成)、出版日期(格式:1998-10-09)、价格,生成Book对象,构造包含4本书的数组
    for(int i=0;i<4;i++){
    String name = scan.next();
    String date_str = scan.next();
    Date date = null;
    //将键盘录入的日期字符串转换为Date
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    try {
    date = sdf.parse(date_str);
    } catch (ParseException e) {
    System.out.println("日期格式有误");;
    }

    double price = Double.parseDouble(scan.next());

    Book book = new Book(name, date, price);
    books[i] = book;
    }

    //2.将books按照出版日期降序排序;然后输出books
    Arrays.sort(books, new BookComparatorByPubDate());
    for(Book book:books){
    System.out.println(book);
    }

    //3.将books按照价格升序排序,如果价格相同,则按照书名字母顺序排列。然后输出books
    Arrays.sort(books, new BookComparatorByPrice());
    for(Book book:books){
    System.out.println(book);
    }

    scan.close();
    }

    }

    /* 请在这里填写答案 */

    输入样例:

    Java
    2011-08-01
    29
    Python
    2014-01-01
    48
    C
    2004-09-08
    17.5
    DataBase
    2012-09-17
    17.5

    输出样例:

    书名:Python,定价:48.0
    书名:DataBase,定价:17.5
    书名:Java,定价:29.0
    书名:C,定价:17.5
    书名:C,定价:17.5
    书名:DataBase,定价:17.5
    书名:Java,定价:29.0
    书名:Python,定价:48.0

    实现代码:

    class Book
    {
    public String name;
    public double price;
    public Date publishDate;
    public Book(){}
    public Book(String name,Date date,double price)
    {
    this.name = name; this.publishDate = date;
    this.price = price;
    }

    @Override
    public String toString()
    {
    return "书名:" + name +",定价:" + price;
    }
    }

    class BookComparatorByPubDate implements Comparator
    {
    public int compare(Object o1,Object o2)
    {
    Book book1 = (Book) o1;
    Book book2 = (Book)o2;
    return -(book1.publishDate.compareTo(book2.publishDate));
    }
    }

    class BookComparatorByPrice implements Comparator
    {
    public int compare(Object o1,Object o2)
    {
    Book book1 = (Book)o1;
    Book book2 = (Book)o2;
    if(book1.price == book2.price)
    {
    return book1.name.compareTo(book2.name);
    }
    else
    {
    if(book1.price – book2.price > 0)
    {
    return 1;
    }
    return -1;
    }
    }
    }

    6-20 Book类的设计

    阅读测试程序,设计一个Book类。

    函数接口定义:

    class Book{}

    该类有 四个私有属性 分别是 书籍名称、 价格、 作者、 出版年份,以及相应的set 与get方法;该类有一个含有四个参数的构造方法,这四个参数依次是书籍名称、 价格、 作者、 出版年份 。

    裁判测试程序样例:

    import java.util.*;
    public class Main {
    public static void main(String[] args) {
    List <Book>books=new ArrayList<Book>();
    Scanner in=new Scanner(System.in);
    for(int i=0;i<5;i++)
    { String str=in.nextLine();
    String []data=str.split(",");
    Book book=new Book(data[0],Integer.parseInt(data[1]),data[2],Integer.parseInt(data[3]));
    books.add(book);
    }

    System.out.println(totalprice(books));
    }

    /*计算所有book的总价*/
    public static int totalprice(List <Book>books)
    { int result=0;
    for(int i=0;i<books.size();i++){result+=books.get(i).getPrice();}
    return result;
    }
    }

    /* 请在这里填写答案 */

    输入样例:

    三体,100,无名氏,1998
    上下五千年,50,编辑部,2015
    海底世界,50,无名氏2,2000
    三体1,100,无名氏3,2017
    三体3,100,无名氏4,1998

    输出样例:

    400

    实现代码:

    class Book{
    //书籍名
    private String name;
    //价格
    private int price;
    //作者
    private String author;
    //出版年份
    private int year;
    //有参构造方法
    Book(String name,int price,String author,int year){
    this.name = name;
    this.price = price;
    this.author = author;
    this.year = year;
    }
    //四个成员相应的set与get方法
    //name
    public void setName(String name){
    this.name = name;
    }
    public String getName(){
    return name;
    }
    //price
    public void setPrice(int price){
    this.price = price;
    }
    public int getPrice(){
    return price;
    }
    //autor
    public void setAuthor(String author){
    this.author = author;
    }
    public String getAuthor(){
    return author;
    }
    //year
    public void setYear(int year){
    this.year = year;
    }
    public int getYear(){
    return year;
    }
    }

    6-21 教师、学生排序

    已知Main类、Person类的设计,完成Student类,Teacher类、MyTool类的设计。

    函数接口定义:

    class Student extends Person{ }
    class Teacher extends Person{ }
    class MyTool{ public static void separateStu_T(List persons,List teachers,List students){} }

    Student类继承了Person,拥有私有属性int类型的sno和String类型的major,分别代表学号与所学专业;提供对应的set,get方法;比较方法完成按照学号比较。
    Teacher类继承了Person,拥有私有属性int类型的tno和String类型的subject,分别代表教师编号与所授科目;提供对应的set,get方法;比较方法完成按年龄比较。
    MyTool类中提供方法public static void separateStu_T(List persons,List teachers,List students){},方法 separateStu_T的功能是将persons线性表中的 teacher,student分别放到teachers,students两个线性表中。

    裁判测试程序样例:

    import java.util.*;

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

    List persons=getPersons(); //得到一个所有人的线性表

    List teachers=new ArrayList();
    List students=new ArrayList();

    MyTool.separateStu_T( persons,teachers,students); //将persons线性表中的 teacher,student分别放到teachers,students两个线性表中

    Collections.sort(teachers); //对教师线性表排序
    Collections.sort(students); //对学生线性表排序

    showResult(teachers); //显示教师线性表排序以后的结果
    showResult(students); //显示学生线性表排序以后的结果

    }

    public static List getPersons()
    {
    List persons=new ArrayList();

    Scanner in=new Scanner(System.in);
    Person person=null;

    int num=Integer.parseInt(in.nextLine());

    for(int i=0;i<num;i++)
    { String str=in.nextLine();
    String []data=str.split(",");

    if(data[0].equalsIgnoreCase("student"))
    person=new Student(Integer.parseInt(data[1]),data[2],data[3],Integer.parseInt(data[4]),data[5]);
    else if (data[0].equalsIgnoreCase("teacher"))
    person=new Teacher(Integer.parseInt(data[1]),data[2],data[3],Integer.parseInt(data[4]),data[5]);
    else person=null;
    persons.add(person);
    }
    return persons;
    }

    public static void showResult(List persons)
    {
    for(int i=0;i<persons.size();i++)
    {
    Person per=(Person)persons.get(i);
    System.out.println(per.getName()+","+per.getGender()+","+per.getAge());
    }
    }

    }

    abstract class Person implements Comparable
    { private String name;
    private String gender;
    private int age;

    public String getName() {
    return name;
    }

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

    public String getGender() {
    return gender;
    }

    public void setGender(String gender) {
    this.gender = gender;
    }

    public int getAge() {
    return age;
    }

    public void setAge(int age) {
    this.age = age;
    }

    public Person(String name, String gender, int age) {
    super();
    this.name = name;
    this.gender = gender;
    this.age = age;
    }

    }

    /* 请在这里写你的代码 */

    输入样例:

    输入的第一行是总人数n,紧跟着输入n行,每一行代表一个人的信息。下面的例子中n=5,输入了5个人的信息。

    5
    student,1001,Tom1,female,18,computer
    teacher,2001,Jake1,female,35,datastructer
    student,1002,Tom2,male,19,computer
    student,1003,Tom3,female,20,software
    teacher,2002,Jake2,female,33,database

    输出样例:

    注意:本样例输出结果中两名教师是按照年龄升序排序的,三名学生是按照学号降序排序的。

    Jake2,female,33
    Jake1,female,35
    Tom3,female,20
    Tom2,male,19
    Tom1,female,18

    实现代码:

    class MyTool{
    public static void separateStu_T(List persons,List teachers,List students){
    Iterator It = persons.iterator();

    while( It.hasNext()){

    Person p= (Person) It.next();
    if(p instanceof Teacher){
    teachers.add((Teacher)(p));
    }
    else{// if( It.next() instanceof Student){
    students.add((Student)(p));
    }
    }

    }
    }
    class Student extends Person{
    private int sno;
    private String major;

    public Student(int sno, String name, String gender, int age, String major) {
    super(name, gender, age);
    this.sno = sno;
    this.major = major;
    // TODO Auto-generated constructor stub
    }

    @Override
    public int compareTo(Object arg0) {
    // TODO Auto-generated method stub

    return -(this.sno – ((Student)arg0).getSno());
    }

    public int getSno() {
    return sno;
    }

    public void setSno(int sno) {
    this.sno = sno;
    }

    public String getMajor() {
    return major;
    }

    public void setMajor(String major) {
    this.major = major;
    }
    }

    class Teacher extends Person{
    private int ton;
    private String subject;

    public Teacher(int tno, String name, String gender, int age, String sub) {
    super(name, gender, age);
    this.ton = ton;
    this.subject = sub;
    // TODO Auto-generated constructor stub
    }

    @Override
    public int compareTo(Object arg0) {
    // TODO Auto-generated method stub
    return this.getAge() – ((Teacher)arg0).getAge();
    }

    }

    6-22 数组工具类的设计

    本题要求设计一个名为MyArrays的类,根据调用的方式实现相应的方法。

    函数接口定义:

    请同学根据该类的调用方式和结果,自行设计MyArrays类中的方法,满足应用的需要。

    裁判测试程序样例:

    import java.util.Scanner;

    public class Main {

    public static void main(String[] args) {

    Scanner sc=new Scanner(System.in);
    int n=sc.nextInt();

    int array[]= new int[n];

    for(int i=0;i<n;i++)
    {
    array[i]=sc.nextInt();
    }

    MyArrays.printArray(array);//显示数组的内容
    MyArrays.sortArray(array); //对数组元素排序
    MyArrays.printArray(array);//显示排序后的结果
    int sum=MyArrays.sumOfArray(array);//数组元素求和
    System.out.println(sum);//显示数组元素的和

    }

    }

    /* 请在这里填写MyArrays类的有关代码 */

    输入样例:

    5
    5 4 6 8 3

    输出样例:

    5,4,6,8,3
    3,4,5,6,8
    26

    实现代码:

    class MyArrays{
    public static void printArray(int arry[]) {
    for(int i=0;i<arry.length-1;i++) {
    System.out.printf("%d,", arry[i]);
    }
    System.out.println(arry[arry.length-1]);
    }
    public static void sortArray(int arry[]) {
    int m,i,j;
    for(i=0;i<arry.length;i++) {
    for(j=0;j<arry.length;j++) {
    if(arry[i]<arry[j]) {
    m=arry[i];arry[i]=arry[j];arry[j]=m;//从小到大排序
    }
    }
    }
    }
    public static int sumOfArray(int array[])
    {
    int sum=0;
    for(int i=0;i<array.length;i++) {
    sum+=array[i];
    }
    return sum;
    }
    }

    赞(0)
    未经允许不得转载:171主机测评 » sdut-Java面向对象-05 类和对象(函数题:12-22题)
    分享到: 更多 (0)

    评论 抢沙发

    • 昵称 (必填)
    • 邮箱 (必填)
    • 网址