initial- - - 2023-03-08 22:02 采纳率: 86.7%
浏览 89
已结题

java小车运行1111

定义一个小车类Car,其初始位置为(0,0),属性包括:当前位置,行驶速度,行驶朝向(东1、南2、西3、北4);方向变化:直行(1)、左转(2)、右转(3);速度变化(正数为加速,负数为减速)。

约束条件:(1)采用直角坐标系,上北下南左西右东;(2)速度为0时,车辆停止,减速无效;(3)速度达到20时,加速无效。输入

小车的初始位置(x,y)、初始速度(v)和初始朝向(f),时刻数量(<=1000),每个时刻内的方向变化(c)、速度变化(s)
输出

当前小车的位置
样例输入 Copy

0 0 0 1
10
1 1 1 1 1 1 1 0 1 0 1 0 2 0 1 0 1 2 1 -1
样例输出 Copy

15,15

  • 写回答

1条回答 默认 最新

  • CodeBytes 2023-03-08 22:09
    关注

    该回答引用ChatGPT

    以下是Java代码实现,可以通过LeetCode的Java环境进行测试:

    
    public class Car {
        private int x;
        private int y;
        private int velocity;
        private int direction;
    
        public Car(int x, int y, int velocity, int direction) {
            this.x = x;
            this.y = y;
            this.velocity = velocity;
            this.direction = direction;
        }
    
        public void move(int changeDirection, int changeVelocity) {
            if (velocity == 0) {
                return;
            }
    
            // 更新速度
            velocity += changeVelocity;
            if (velocity < 0) {
                velocity = 0;
            } else if (velocity > 20) {
                velocity = 20;
            }
    
            // 更新方向
            direction = (direction + changeDirection) % 4;
            if (direction == 0) {
                direction = 4;
            }
    
            // 根据方向和速度更新位置
            switch (direction) {
                case 1:
                    x += velocity;
                    break;
                case 2:
                    y -= velocity;
                    break;
                case 3:
                    x -= velocity;
                    break;
                case 4:
                    y += velocity;
                    break;
            }
        }
    
        public String getPosition() {
            return x + "," + y;
        }
    }
    
    public class Main {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            int x = scanner.nextInt();
            int y = scanner.nextInt();
            int velocity = scanner.nextInt();
            int direction = scanner.nextInt();
            int n = scanner.nextInt();
            Car car = new Car(x, y, velocity, direction);
    
            for (int i = 0; i < n; i++) {
                int changeDirection = scanner.nextInt();
                int changeVelocity = scanner.nextInt();
                car.move(changeDirection, changeVelocity);
            }
    
            System.out.println(car.getPosition());
        }
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 6月18日
  • 已采纳回答 6月18日
  • 创建了问题 3月8日