JAVA期中测试

发布于 2019-10-21  131 次阅读


第一题

// 利用ArrayList创建一个集合,存放多个整数,并将偶数输出。
import java.util.ArrayList; 
public class Q1 {
    public static void main(String[] args) {

        ArrayList even=new ArrayList();
        for(int i=1;i<=20;i++){
            even.add(i);
        }
        for(int j=0;j<even.size();j++){
            even.remove(j);
        }
        System.out.println(even);
    }
}

第二题

/*
设计一个汽车类Vehicle

包含属性:
(1)品牌brand
(2)颜色color
(3)速度speed

构造器:有参数,速度的初始值为0,其他由参数决定
run()方法:输出字符串”什么品牌什么颜色的汽车在以多少的速度在行驶“
要求:只写类的定义即可。
*/
public class Vehicle {
    public String brand, color;
    public int speed;

    public Vehicle(String brand, String color, int speed) {
        super();
        this.brand = brand;
        this.color = color;
        this.speed = speed;
    }

    public String getBrand() {
        return brand;
    }
    public String getColor() {
        return color;
    }
    public void setColor(String color) {
        this.color = color;
    }
    public double getSpeed() {
        return speed;
    }
    public void setSpeed(int speed) {
        this.speed = speed;
    }

    public void run() {
        System.out.println("品牌:"+brand+" 颜色:"+color+" 速度:"+speed);
    }

    public static void main(String[] args) {
        Vehicle a=new Vehicle("aa","red",12);
        a.run();
    }

}

第三题

/*
定义一个接口Comp,接口中有一个方法compute(),方法有两个整型参数。
定义接口的四个实现类,分别实现加、减、乘、除四种运算。
定义一个UseComp类,类中有一个方法,参数分别为(Comp,int,int),根据具体传入的对象完成加减乘除计算。
*/

public interface Comp {
       float compute(int x,int y);
}

class Add implements Comp{
       public float compute(int x, int y) {
              return x+y;
       }
}

class Minus implements Comp {
       public float compute(int x, int y) {
              return x-y;
       }
}

class Division implements Comp {
       public float compute(int x, int y) {
              return (float)x/(float)y;
       }
}

class Multiply implements Comp {
       public float compute(int x, int y) {
              return (float)x*(float)y;
       }
}

class UseComp {
       float run(Comp c,int x,int y){
              return c.compute(x, y);
       }
}

public class Test {
       public static void main(String[] args) {
              UseComp uc = new UseComp();
              System.out.println(uc.run(new Add(), 5, 2));
              System.out.println(uc.run(new Minus(), 5, 2));
              System.out.println(uc.run(new Multiply(), 5, 2));
              System.out.println(uc.run(new Division(), 5, 2));
       }

}


我们都要做生活的高手。