填空题&&函数题部分

填空题:

 

 

 

函数题:

是否偶数:

import java.util.Scanner;
public class Main {

    public static void main(String[] args) {
        Scanner in=new Scanner(System.in);
        int data=in.nextInt();
        System.out.println(isOdd(data));
    }


    /* 请在这里给出isOdd(i)函数 */


}

代码:

public static boolean isOdd(int data){
        if(data%2 == 0){
            return true;
        }
        else
            return false;
    }
View Code

TDVector:

import java.util.Scanner;
class TDVector {
    private double x;
    private double y;
    public String toString() {
        return "("+this.x+","+this.y+")";
    }

    /** 你所提交的代码将被嵌在这里(替换此行) **/

}

public class Main {
    public static void main(String[] args) {
        TDVector a = new TDVector();  //    default ctor, x and y are zeros
        Scanner sc = new Scanner(System.in);
        double x,y,z;
        x = sc.nextDouble();
        y = sc.nextDouble();
        z = sc.nextDouble();        
        TDVector b = new TDVector(x, y);    //  ctor by x and y
        TDVector c = new TDVector(b);       //  ctor by another TDVector
        a.setY(z);
        System.out.println(a);
        System.out.println(b);
        System.out.println(c);
        c.setX(z);
        a = b.add(c);
        System.out.println(a);
        System.out.println("b.x="+b.getX()+" b.y="+b.getY());
        sc.close();
    }
}

代码:

public double getX() {
        return x;
    }

    public void setX(double x) {
        this.x = x;
    }

    public double getY() {
        return y;
    }

    public void setY(double y) {
        this.y = y;
    }
    TDVector(){
        this.x = this.y = 0;
    }
    TDVector(double x, double y){
        this.x = x;
        this.y = y;
    }
    TDVector(TDVector object){
        this.x = object.x;
        this.y = object.y;
    }
    public TDVector add(TDVector n){
        n.x += this.x;
        n.y += this.y;
        return n;
    }
View Code

Book类的设计:

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

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

代码:

class Book{
    private String name;
    private double price;
    private String author;
    private double publishyear;
    Book(String name, double price, String author, double publishyear){
        this.name = name;
        this.price= price;
        this.author = author;
        this.publishyear = publishyear;
    }

    public String getName() {
        return name;
    }

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

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public double getPublishyear() {
        return publishyear;
    }

    public void setPublishyear(double publishyear) {
        this.publishyear = publishyear;
    }
    
}
View Code

重写父类法equals:

import java.util.Scanner;
class Point {
private int xPos, yPos;
public Point(int x, int y) {
    xPos = x;
    yPos = y;
    }
@Override
/* 请在这里填写答案 */
}
public class Main {
    public static void main(String[] args) {
       Scanner sc = new Scanner(System.in);
       Object p1 = new Point(sc.nextInt(),sc.nextInt());
       Object p2 = new Point(sc.nextInt(),sc.nextInt());
       System.out.println(p1.equals(p2));
      sc.close();
}
}

代码:

 public boolean equals(Object obj){
        if(this == obj)
            return true;
        if(obj == null || this.getClass() != obj.getClass())
            return false;
        Point point = (Point) obj;
        return this.xPos == point.xPos && this.yPos == point.yPos;
    }
View Code

创建一个直角三角形类实现IShape接口:

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

代码:

class RTriangle implements IShape{
    private double a;
    private double b;
    RTriangle(double a, double b){
        this.a = a;
        this.b = b;
    }
    public double getArea(){
        return a*b*0.5;
    }
    public double getPerimeter(){
        return a+b+Math.sqrt(a*a+b*b);
    }

}
View Code

判断一个数列是否已排好序:

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int[] list = new int[20];
        list[0] = input.nextInt();
        for (int i=1; i<= list[0]; i++)
            list[i] = input.nextInt();
        if (isSorted(list))
            System.out.println("The list is already sorted");
        else
            System.out.println("The list is not sorted");
    }

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

}

代码:

public static boolean isSorted(int[] list)
        {
            int i,j,x;
            x=list[1];
            int flag=0;
            for(i=1;i<=list[0];i++)
        {     
               if(x>list[i])
        {      
                   flag=1;
                 break;
        }
                x=list[i];
        }
            if(flag==0)
                return true;
            else
                return false;
        }
View Code

编写Matrix类,使用二维数组实现矩阵,实现两个矩阵的乘法:

import java.util.Scanner;
public class Main {    
    public static void main(String[] args) {    
        Matrix firstMat=Matrix.inputMatrix();        
        Matrix secondMat=Matrix.inputMatrix();        
        //display(firstMat.matrix);    display(secondMat.matrix);            

        Matrix productMat=firstMat.multiply(secondMat);
        display(productMat.matrix);        
    }    

    //display方法:打印二维数组元素到屏幕
    public static void display(int[][] array){
        for(int i=0; i<array.length; i++){
            for(int j=0; j<array[i].length; j++){
                if(j==array[i].length-1) {
                    System.out.println(array[i][j]);
                }
                else {
                    System.out.print(array[i][j]+" ");
                }
            }
        }
    }
}

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

 

代码:

class Matrix{
    int row, column, matrix[][];
    static Scanner reader = new Scanner(System.in);
    public static Matrix inputMatrix(){
        Matrix mat = new Matrix();
        mat.row = reader.nextInt();
        mat.column = reader.nextInt();
        mat.matrix = new int[mat.row][mat.column];
        for(int i=0; i< mat.row; i++){
            for(int j=0; j< mat.column; j++){
                mat.matrix[i][j] = reader.nextInt();
            }
        }
        return mat;
    }
    Matrix multiply(Matrix m){
        int col = m.matrix[0].length;
        Matrix res = new Matrix();
        res.matrix = new int[row][col];
        for(int i=0; i<row; i++){
            for(int j=0; j<col; j++){
                for(int k=0; k<column; k++){
                    res.matrix[i][j] += matrix[i][k] * m.matrix[k][j];
                }
            }
        }
        return res;
    }
}
View Code

根据已有类Worker,使用LinkedList编写一个WorkerList类,实现计算所有工人总工资的功能:

import java.util.*;

public class Main {
    public static void main(String[] args) {        
        WorkerList app=new WorkerList();                        
        List<Worker> list=app.constructWorkerList();        
        System.out.println(app.computeTotalSalary(list));    
    }
}

/* 请在这里填写答案:将WorkerList类补充在这里 */


class Worker {    
    private String name;
    private double salary;

    public Worker() { }

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

    public String getName() {
        return name;
    }

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

    public double getSalary(){
        return salary;
    }

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

    public String toString() {
        return name + " "+salary;
    }    
}

 

代码:

class WorkerList{
    Worker readInWorker(){
        Scanner sc = new Scanner(System.in);
        Worker worker = new Worker();
        String name = sc.next();
        double salary = sc.nextDouble();
        worker.setName(name);
        worker.setSalary(salary);
        return worker;
    }
    List<Worker> constructWorkerList(){
        Scanner sc = new Scanner(System.in);
        List<Worker> list = new ArrayList<Worker>();
        int workerNum = sc.nextInt();
        String name;
        double salary;
        for (int i=0; i<workerNum; i++){
            Worker worker = new Worker();
            name = sc.next();
            salary = sc.nextDouble();
            worker.setName(name);
            worker.setSalary(salary);
            list.add(worker);
        }
        return list;
    }
    double computeTotalSalary(List<Worker> list){
        double sum = 0;
        for(int i=0; i<list.size(); i++){
            sum += list.get(i).getSalary();
        }
        return sum;
    }
}
View Code

根据要求,使用泛型和LinkedList编写StringList类,实现QQ号码查找的功能:

import java.util.*;

public class Main {    
    public static void main(String[] args) {
        String[] strs = {"12345","67891","12347809931","98765432102","67891","12347809933"};
        StringList sl=new StringList();
        LinkedList<String> qqList=sl.constructList(strs);
        System.out.println(sl.search(qqList));
    }
}

/* 请在这里填写答案:StringList类 */

代码:

class StringList {
    private String strs;

    public String getStrs() {
        return strs;
    }

    public void setStrs(String strs) {
        this.strs = strs;
    }
    LinkedList constructList(String[] strs){
//        this.strs = strs;
        LinkedList<String> list = new LinkedList();
        for(int i=0; i<strs.length; i++){
            list.add(strs[i]);
        }
        return list;
    }
    String search(LinkedList list){
        Scanner sc=new Scanner(System.in);
        int len = sc.nextInt();
        int flag = 0;
        String temp = null;
        for(int i=0; i<list.size(); i++){
            temp = (String)list.get(i);
            if(temp.length() == len){
                flag = 1;
                break;
            }
        }
        if(flag == 1)
            return temp;
        else
            return "not exist";
    }
}
View Code

根据要求,使用泛型和LinkedList编写StringList类,统计某个指定位数(长度)的QQ号码的数量:

import java.util.LinkedList;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        String[] strs = {"12345","67891","12347809931","98765432102","67891","12347809932","12347809934"};
        StringList sl=new StringList();
        LinkedList<String> qqList=sl.constructList(strs);
        System.out.println(sl.search(qqList));    
    }
}

/* 请在这里填写答案:StringList类 */

代码:

class StringList {
    private String strs;

    public String getStrs() {
        return strs;
    }

    public void setStrs(String strs) {
        this.strs = strs;
    }
    LinkedList constructList(String[] strs){
//        this.strs = strs;
        LinkedList<String> list = new LinkedList();
        for(int i=0; i<strs.length; i++){
            list.add(strs[i]);
        }
        return list;
    }
    String search(LinkedList list){
        Scanner sc=new Scanner(System.in);
        int len = sc.nextInt();
        int flag = 0;
        String temp = null;
        for(int i=0; i<list.size(); i++){
            temp = (String)list.get(i);
            if(temp.length() == len){
                flag ++;
            }
        }
        if(flag != 0)
        {
            String result = flag + "";
            return result;
        }
        else
            return "-1";
    }
}
View Code

List中指定元素的删除:

public class Main {

    /*covnertStringToList函数代码*/   

    /*remove函数代码*/

     public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNextLine()){
            List<String> list = convertStringToList(sc.nextLine());
            System.out.println(list);
            String word = sc.nextLine();
            remove(list,word);
            System.out.println(list);
        }
        sc.close();
    }

}

代码:

public static List<String> convertStringToList(String line){
        List<String> list = new ArrayList<String>();
        String s[] = line.split("\s+");
        for(int i=0; i<s.length; i++){
            list.add(s[i]);
        }
        return list;
    }
    /*在list中移除掉与str内容相同的元素*/
    public static void remove(List<String> list, String str){
        List<String> s = new ArrayList<String>();
        s.add(str);
        list.removeAll(s);
    }
View Code

教师、学生排序:

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


}

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

代码:

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

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

    @Override
    public int compareTo(Object o) {
        return -(this.sno - ((Student)o).getSno());
    }
}
class Teacher extends Person{
    private int tno;
    private String subject;
    public Teacher(int tno, String name, String gender, int age, String sub) {
        super(name, gender, age);
        this.tno = tno;
        this.subject = sub;
    }

    @Override
    public int compareTo(Object arg0) {
        // TODO Auto-generated method stub
        return this.getAge() - ((Teacher)arg0).getAge();
    }
}
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
                students.add((Student)(p));
        }
    }
}
View Code

面向对象基础-覆盖与equals:

public boolean equals(Object obj)

输入:

Company c1 = new Company("MicroSoft");
Company c2 = new Company("IBM");
Person e1 = new Employee("Li", 35, true, 60000.124, c1);
Person e2 = new Employee("Li", 35, true, 60000.124, c1);
Person e3 = new Employee("Li", 35, true, 60000.124, c2);
Person e4 = new Employee("Li", 35, true, 60000.123, c2);
Person e5 = new Employee("Li", 35, true, 60000.126, c2);
Person e6 = new Employee("Li", 35, true, 60000.126, null);
System.out.println(e1.equals(e2));
System.out.println(e1.equals(e3));
System.out.println(e3.equals(e4));
System.out.println(e3.equals(e5));
System.out.println(e5.equals(e6));

输出:

true
false
true
false
false

 代码:

public boolean equals(Object obj)
{
    if(obj instanceof Employee){
        Employee emp = (Employee)obj;
        if(super.equals(emp) && ((this.company == null && emp.company == null) || (this.company != null && this.company.equals(emp.company)))){
            DecimalFormat df = new DecimalFormat("#.##");
        if(df.format(this.salary).equals(df.format(emp.salary)))
            return true;
        }
     }

     return false;
}
View Code

图书和音像租赁:

import java.util.Scanner;

public class Main {
        public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        Media[] ms  = new Media[n];
        for (int i=0; i<n; i++) {
            String type = sc.next();
            if (type.equals("book")) {
                ms[i] = new Book(sc.next(), sc.nextDouble());
            }else {
                ms[i] = new DVD(sc.next());
            }
        }
        double rent = MediaShop.calculateRent(ms, sc.nextInt());
        System.out.printf("%.2f", rent);
    }
}

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

输入:

5
book Earth 25.3
book Insights 34
dvd AI
dvd Transformer
book Sun 45.6
20

输出:

60.98

代码:

class Media{
    String name;
    String type;
    double price;
    double rent_price;
    double rent;
    public Media() {}
}
class Book extends Media{
    public Book(){}
    public Book(String name,double price){
        this.name=name;
        this.price=price;
        this.rent_price=0.01*price;
    }
    public String getName(){
        return this.name;
    }
    public double getDays(){
        return this.price;
    }
    double getDailyRent(){
        return this.rent_price;
    }
}
class DVD extends Media{
    public DVD(){}
    public DVD(String name){
        this.name=name;
        this.rent_price=1;
    }
    public String getName(){
        return this.name;
    }
    double getDailyRent(){
        return this.rent_price;
    }
}
class MediaShop{
    public static double calculateRent(Media[] medias, int days){
        double sum=0;
        for(int i=0;i<medias.length;i++){
            if(medias[i].type =="book"){
                sum+=medias[i].rent_price*days;
            }
            else{
                sum+=medias[i].rent_price*days;
            }
        }
        return sum;
    }
}
View Code

设计门票(抽象类):

 

public class Main{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        Ticket a = new WalkupTicket(in.nextInt());
        System.out.println(a.toString());
        Ticket b = new AdvanceTicket(in.nextInt(), in.nextInt());
        System.out.println(b.toString());
        Ticket c = new StudentAdvanceTicket(in.nextInt(), in.nextInt(), in.nextInt());
        System.out.println(c.toString());
    }
}

/* 请在这里填写答案 */
abstract class Ticket {
……
}
class WalkupTicket extends Ticket {
……
}
class AdvanceTicket extends Ticket {
……
}
class StudentAdvanceTicket extends AdvanceTicket {
……
}
//设计框架

代码:

// package 实验二2;
import java.util.*;

abstract class Ticket {
    int number;
    public Ticket(int number) {
        this.number=number;
    }
    abstract public int getPrice();
    abstract public String toString();
}

class WalkupTicket extends Ticket {
    int price;
    public WalkupTicket(int number) {
        super(number);
        this.price=50;
    }
    
    public int getPrice() {
        return this.price;
    }
    
    public String toString() {
        return "Number:"+this.number+",Price:"+this.price;
    }
}

class AdvanceTicket extends Ticket {
    int leadTime;
    int price;
    public AdvanceTicket(int number,int leadTime) {
        super(number);
        this.leadTime=leadTime;
        if(leadTime>10)this.price=30;
        else           this.price=40;
    }
    
    public int getPrice() {
        return this.price;
    }
    public String toString() {
        return "Number:"+this.number+",Price:"+this.price;
    }
    
}
class StudentAdvanceTicket extends AdvanceTicket {
    int height;
    int price;
    public StudentAdvanceTicket(int number,int leadTime,int height) {
        super(number,leadTime);
        this.height=height;
        if(height>120) {
            if(leadTime>10)this.price=20;
            else           this.price=30;
        }else {
            if(leadTime>10)this.price=10;
            else           this.price=15;
        }
    }
    
    public int getPrice() {
        return this.price;
    }
    
    public String toString() {
        return "Number:"+this.number+",Price:"+this.price;
    }
}
View Code
原文地址:https://www.cnblogs.com/3cH0-Nu1L/p/14771896.html