类与对象练习一 :请定义一个交通工具(Vehicle)的类

来源:互联网 发布:查看iphone网络制式 编辑:程序博客网 时间:2024/06/01 07:38

课堂练习1

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

 1. 属性:速度(speed),体积(size)等

 2.方法:移动(move()),设置速度(setSpeed(int speed)),设置体积(setSize(int size))加速speedUp(),减速speedDown()等

在测试类Vehicle中的main()中实例化一个交通工具对象,通过方法给它初始化speed,size的值,并打印出来。另外,调用加速,减速的方法对速度进行改变。



1.代码

(1)主类 TestVehicle.java

import java.util.Scanner;

public class TestVehicle {

public static void main(String[]args) {

 Scanner sc=new Scanner(System.in);            //创建对象sc

 int sp=sc.nextInt(); //输入速度sp的值

 int si=sc.nextInt(); //输入体积si的值

 Vehicle car=new Vehicle(); //创建交通工具对象car

 car.setSpeed(sp); //调用setSpeed方法,给速度赋值

car.setSize(si); //调用setSize方法,给体积赋值

car.printvehicle(); //调用printvehicle方法,输出car的速度和体积

System.out.print("汽车的速度增加了:");

int up=sc.nextInt(); //输入速度增加的值

car.speedUp(car,up); //调用speedUp方法,输出速度增加后的值

System.out.print("汽车的速度减少了:");

int down=sc.nextInt(); //输入速度减少的值

        car.speedDown(car,down); //调用speedDown方法,输出速度减少之后的值

}

}

(2) Vehicle.java

 

public class Vehicle {

int speed;

int size;

int up;

int down;

void move() {//定义方法move

 

}

    void setSpeed(int sp ) {//定义方法setSpeed ,为speed赋值

  speed=sp;

}

void setSize(int si) {//定义方法setSize,为size赋值

size=si;

}

void printvehicle() {//定义方法printvehicle,输出汽车速度和体积

System.out.println("汽车的速度为"+speed+"千米/时");

System.out.println("汽车的体积为"+size+"立方米");

}

void speedUp(Vehiclecarr,int upp) {//定义方法speedUp,输出加速后的速度

up=carr.speed+upp;

System.out.println("汽车加速后的速度为:"+up+"千米/时");

}

void speedDown(Vehiclecarr,int downn) {//定义方法speedDown,输出减速后的速度

down=carr.speed-downn;

System.out.println("汽车减速后的速度为:"+down+"千米/时");

}

}

2.运行截图

阅读全文
0 0
原创粉丝点击