题目:
请定义一个交通工具(Vehicle)的类,其中有:属性:速度(speed),体积(size)等等
方法:移动(move()),设置速度(setSpeed(int speed)),加速speedUp(),减速speedDown()等等.
最后在测试类Vehicle中的main()中实例化一个交通工具对象,并通过方法给它初始化speed,size的值,
并且通过打印出来。另外,调用加速,减速的方法对速度进行改变。
代码:
import java.util.Scanner; class Vehicle{ int speed; String size; Vehicle(){} Vehicle(String size){ //@overload构造方法重载 this.size = size; } public void prt(String a){ System.out.println(a); } public void move(){ prt("您的"+this.size+"寸爱车启动.."); } public void setSpeed(int speed){ this.speed = speed; } public void speedUp(){ this.speed += 10; prt("爱车速度现在是"+this.speed); } public void speedDown(){ if(this.speed>15){ prt("刹车中......"); this.speed -= 15; prt("爱车速度现在是"+this.speed); }else{ this.speed = 0; prt("已停车!!"); } } public void speedDown(int a){ //成员方法重载 if(this.speed>15){ prt("刹车中......"); if((this.speed-a)<15){ this.speed -= 5; }else{ this.speed -= 15; } prt("爱车速度现在是"+this.speed); }else{ this.speed = 0; prt("已停车!!"); } } } class Driving{ public static void main(String[] args){ Vehicle c1 = new Vehicle("100"); Scanner sc = new Scanner(System.in); c1.move(); System.out.println("请设置巡航速度"); int n = sc.nextInt(); c1.setSpeed(n); System.out.println("已设定车速为"+c1.speed); System.out.println("前方有连续弯道,请减速至30"); while(c1.speed>30){ c1.speedDown(30); } System.out.println("弯道已过,请加速至60"); while(c1.speed<60){ c1.speedUp(); } System.out.println("到达目的地,请停车"); while(c1.speed>0){ c1.speedDown(); } } }