java面向对象作业01

1.猜数字游戏:一个类A有两个成员变量vnumv有一个初值100。定义一个方法guess,对A类的成员变量v,用num进行猜。如果大了则提示大了,小了则提示小了。等于则提示猜测成功。

main方法中测试

 1 public class test5 {
 2     private int num = 100;
 3     public int yours;
 4     public test5(){
 5         System.out.println("创建对象。");
 6     }
 7     public void guess(){
 8         if(yours>num){
 9             System.out.println("big");
10         }
11         else if(yours<num){
12             System.out.println("small");
13         }
14         else{
15             System.out.println("right");
16         }
17     }
18     public static void main(String[] args){
19         test5 c = new test5();
20         c.yours=101;
21         c.guess();
22         c.yours=99;
23         c.guess();
24         c.yours=100;
25         c.guess();
26     }
27 }

2.创建一个圆Circle类。为该类提供一个变量r表示半径,一个常量PI表示圆周率;同时为该类提供两个方法:方法一用于求圆的面积,方法二用于求圆的周长;为该类提供一个无参的构造方法,用于初始化r的值为4。main方法中测试。

public class Circle {
    double PI=3.14;
    double r;
    public Circle(){
        r=4;
    }
    public double areaCircle(){
        double area;
        area=PI*r*r;
        return area;
    }
    public double circlePerimeter(){
        double Perimeter;
        Perimeter=2*PI*r;
        return Perimeter;
    }

    public static void main(String[] args) {
        Circle test=new Circle();
        System.out.println(test.areaCircle());
        System.out.println(test.circlePerimeter());
    }
}

3.请定义一个交通工具(Vehicle)的类,其中有:属性:速度(speed),车的类型(type)等等方法:移动(move()),设置速度(setSpeed(double s)),加速speedUp(double s),减速speedDown(double s)等等.最后在测试类Vehicle中的main()中实例化一个交通工具对象,并通过构造方法给它初始化speed,type的值,并且打印出来。另外,调用加速,减速的方法对速度进行改变。

public class Vehicle {
    double speed;
    String type;
    public Vehicle(){
        type="Lamborghini";
    }
    public void move(){
        System.out.println(type+"正在以"+speed+"km/h的速度行驶");
    }
    public void setSpeed(double speed) {
        this.speed = speed;
    }
    public void speedUp(double speed){
        this.speed+=speed;
        System.out.println(type+"开始加速");
    }
    public void speedDown(double speed){
        this.speed=this.speed-speed;
        System.out.println(type+"开始减速");
    }
    public void down(){
        this.speed=0;
        System.out.println(type+"突然刹车");
        System.out.println(type+"正在以"+speed+"km/h的速度呆在原地");
    }
    public static void main(String[] args) {
        Vehicle test=new Vehicle();
        double speed0=30;
        test.setSpeed(speed0);
        double speed1=40.3;
        double speed2=58.2;
        double speed3=20.1;
        test.move();
        test.speedUp(speed1);
        test.move();
        test.speedDown(speed3);
        test.move();
        test.down();
    }
}

猜你喜欢

转载自www.cnblogs.com/cjs666/p/10909363.html