Java定义一个交通工具(Vehicle)的类,定义私有属性:速度(speed)、方向(direction),定义方法:设置速度setSpeed(int speed))、改变速度changeSpeed(int speed),设置方向setDirection(int direction),改变速度changeDirection(int direction)。最后在测试类Vehicle 中的main()中实例化一个交通工具对象 direction:1:North2:South3:East4:West 输入:一行两个数 第一个数表示调用哪个方法(1:setSpeed 2:changeSpeed 3:setDirection4:changeDirection)第二个数表示输入的值 输出:方法名和私有属性的值初始化速度为0,方向为North例 输入:11输出: setSpeed speed=1 direction=North
时间: 2024-02-26 15:56:37 浏览: 185
好的,以下是你需要的Java代码:
```java
public class Vehicle {
private int speed;
private int direction;
public Vehicle() {
speed = 0;
direction = 1;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public void changeSpeed(int speed) {
this.speed += speed;
}
public void setDirection(int direction) {
this.direction = direction;
}
public void changeDirection(int direction) {
this.direction += direction;
}
public String toString() {
return "speed=" + speed + " direction=" + directionToString();
}
private String directionToString() {
switch (direction) {
case 1:
return "North";
case 2:
return "South";
case 3:
return "East";
case 4:
return "West";
default:
return "Unknown";
}
}
}
```
测试类:
```java
import java.util.Scanner;
public class TestVehicle {
public static void main(String[] args) {
Vehicle vehicle = new Vehicle();
Scanner scanner = new Scanner(System.in);
while (true) {
int method = scanner.nextInt();
int value = scanner.nextInt();
switch (method) {
case 1:
vehicle.setSpeed(value);
System.out.println("setSpeed " + vehicle.toString());
break;
case 2:
vehicle.changeSpeed(value);
System.out.println("changeSpeed " + vehicle.toString());
break;
case 3:
vehicle.setDirection(value);
System.out.println("setDirection " + vehicle.toString());
break;
case 4:
vehicle.changeDirection(value);
System.out.println("changeDirection " + vehicle.toString());
break;
default:
System.out.println("Unknown method");
break;
}
}
}
}
```
使用时,可以在终端输入数字来调用不同的方法,例如输入`1 5`表示调用setSpeed方法,将速度设置为5。输出会显示方法名和私有属性的值。
注意,这里的方向使用数字表示,1表示North,2表示South,3表示East,4表示West。如果需要输出中文方向,可以修改Vehicle类中的directionToString方法。
阅读全文