Java练习(3)

来源:互联网 发布:幕墙易云计算手机 编辑:程序博客网 时间:2024/05/17 23:30

1、 请定义一个交通工具(Vehicle)的类,其中有:

(1)属性:速度(speed),体积(size)等
(2)方法:移动(move()),设置速度(setSpeed(int speed)),设置体积(setSize(int size))加速speedUp(),减速speedDown()等
在测试类Vehicle中的main()中实例化一个交通工具对象,通过方法给它初始化speed,size的值,并打印出来。另外,调用加速,减速的方法对速度进行改变。

import java.util.Scanner;public class TestTVehicle {    public static void main(String[] args) {        Scanner input=new Scanner(System.in);        System.out.print("请输入交通工具的名字:");        String name=input.next();        Vehicle vehicle=new Vehicle();        System.out.println(name+"通过方法设置速度为:"+vehicle.setSpeed(14)+"体积为:"+vehicle.setSize(40));        System.out.println(name+"加速后,当前速度为:"+vehicle.speedUp());        System.out.println(name+"减速后,当前速度为:"+vehicle.speedDown());        }    }public class Vehicle {        int speed,size;        public void Vehicle() {        speed=0;        size=0;        }        int setSpeed(int speed){        this.speed=speed;        return speed;        }        int setSize(int size){        this.size=size;        return size;        }        void move(){        }        int speedUp(){        speed++;        return speed;        }        int speedDown(){        speed--;        return speed;        }}       

这里写图片描述

2、以Point类为基础,定义一个平面中的Circle类:

1、编写一个无参的构造函数;
2、编写一个有参的构造函数;
3、在主函数中调用无参的构造函数生成圆的实例c1,调用有参的构造函数生成圆的实例c2,调用实例方法判断c1和c2是否相重叠。

public class Point {    public static void main(String args[]){        Circle  c1=new Circle();        Circle  c2=new Circle(3,4,5);        c1.printPoint(c2);      }}public class Circle{        int x,y,r;        Circle(){            x=6;            y=4;            r=5;            System.out.println("c1的横坐标是:"+x+"  "+"c1的纵坐标是:"+y+"  " +"c1的半径是:"+ r);    }    Circle(int xx,int yy,int rr){            x=xx;            y=yy;            r=rr;            System.out.println("c2的横坐标是:"+x+"  "+"c2的纵坐标是:"+y+"  " +"c2的半径是:"+ r);    }    public void printPoint(Circle c){        if(c.x==x&&c.y==y&&c.r==r) {             System.out.println("c1与c2重叠");             }else {             System.out.println("c1与c2不重叠");             }     } }

这里写图片描述

原创粉丝点击