定义一个交通工具(Vehicle)的类,定义私有属性: 速度(speed)、方向(direction),定义方法:设置速度setSpeed(int
speed))、改变速度changeSpeed(int speed),设置方向setDirection(int
direction),改变速度changeDirection(int direction)。最后在测试类 Vehicle 中的
main()中实例化一个交通工具对象direction:

1:North

2:South

3:East

4:West

输入:一行两个数

第一个数表示调用哪个方法(1:setSpeed 2:changeSpeed 3:setDirection 4:changeDirection)

第二个数表示输入的值

输出:方法名和私有属性的值

初始化速度为0,方向为North



输入:

1 1

输出:

setSpeed

speed = 1 direction = North

输入用例:

1 1

输出用例:

setSpeed

speed = 1 direction = North

输入用例:

2 1

输出用例:

changeSpeed

speed = 1 direction = North

输入用例:

3 2

输出用例:

setDirection

speed = 0 direction = South

以下为源码:

import java.util.Scanner;

public class Main{

    public static void main(String[] args) {

        Scanner sc=new Scanner(System.in);

            Vehicle vehicle=new Vehicle();

            int n=sc.nextInt();

            int m=sc.nextInt();

            switch (n){

                case 1:  System.out.println("setSpeed");

                        vehicle.setSpeed(m);

                        System.out.print("speed = "+vehicle.getSpeed()+" direction = North");

                        break;

                case 2:  System.out.println("changeSpeed");

                        vehicle.setSpeed(m);

                        System.out.print("speed = "+vehicle.getSpeed()+" direction = North");break;

                case 3:System.out.println("setDirection");

                    vehicle.setDirection(m);

                    System.out.print("speed = 0"+" direction = "+vehicle.str);

                    break;

                case 4:System.out.println("changeDirection");

                    vehicle.setDirection(m);

                    System.out.print("speed = 0"+" direction = "+vehicle.str);

                    break;

                }

    }

}

class Vehicle{

    private int speed=0;

    private int direction;

    String str;

    

    public void setSpeed(int speed){

        this.speed=speed;

    }

    public int getSpeed(){

        return speed;

    }

    public void setDirection(int direction){

        switch (direction){

        case 1:str="North";break;

        case 2:str="South";break;

        case 3:str="East";break;

        case 4:str="West";break;

    }

    }

    public void changeSpeed(int speed){

        this.speed=speed;

    }

    public void changeDirection(int direction){

            switch (direction){

        case 1:str="North";break;

        case 2:str="South";break;

        case 3:str="East";break;

        case 4:str="West";break;

    }   

    }

}

技术
下载桌面版
GitHub
Gitee
SourceForge
百度网盘(提取码:draw)
云服务器优惠
华为云优惠券
腾讯云优惠券
阿里云优惠券
Vultr优惠券
站点信息
问题反馈
邮箱:[email protected]
吐槽一下
QQ群:766591547
关注微信