You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现输入“more”时累加5MPH的车速递增功能?

车速增减功能逻辑修正方案

需求说明

  • 输入more时,车速每次递增5MPH(首次输入输出5,后续依次累加)
  • 输入less时,车速每次递减5MPH
  • 需持续保留上次的车速值
  • 输入quit时退出操作

现有接收输入代码

public static void readInputSpeed(String prompt) {
    System.out.print(prompt);
    String inputSpeed = new Scanner(System.in).nextLine();
    Car.speed(inputSpeed);
}

错误代码问题分析

你尝试的代码存在几个核心逻辑问题:

  1. 字符串比较错误:Java中==比较的是对象引用,不是字符串内容,应该用equals()方法判断输入内容
  2. Scanner重复实例化:每次循环新建Scanner会造成资源浪费,且可能导致输入异常
  3. 冗余的数组与循环:用长度为1的数组和单次for循环完全没必要,直接用单个变量就能保存车速
  4. 车速值重置:循环内将array[i]赋值为i,每次都会重置车速,无法保留历史值

修正后的代码

import java.util.Scanner;

public class YourCarController {
    public static void readInputSpeed(String prompt) {
        Scanner scanner = new Scanner(System.in);
        int currentSpeed = 0;
        String input;

        while (true) {
            System.out.print(prompt);
            input = scanner.nextLine().trim();

            if ("quit".equals(input)) {
                break;
            } else if ("more".equals(input)) {
                currentSpeed += 5;
                System.out.println(currentSpeed + " MPH");
                // 若需同步到Car类,可调用:Car.speed(String.valueOf(currentSpeed));
            } else if ("less".equals(input)) {
                currentSpeed -= 5;
                // 可选:禁止车速为负,取消下方注释即可
                // currentSpeed = Math.max(0, currentSpeed);
                System.out.println(currentSpeed + " MPH");
                // 若需同步到Car类,可调用:Car.speed(String.valueOf(currentSpeed));
            } else {
                System.out.println("无效输入,请输入 more/less/quit");
            }
        }
        scanner.close();
    }
}

代码说明

  • 用int currentSpeed变量持久保存当前车速,初始值为0,每次操作后自动更新
  • 仅创建一次Scanner对象,避免资源浪费与输入异常
  • 使用equals()进行字符串内容比较,确保输入判断准确
  • 用trim()处理输入,过滤用户误输入的前后空格
  • 增加无效输入提示,优化交互体验
  • 可选添加车速非负限制,避免出现负数车速(根据业务需求选择)

内容的提问来源于stack exchange,提问作者Stewl3

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 23:15:21