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

如何将ArrayList搜索结果输出为带返回选项的菜单格式?

ArrayList搜索结果菜单式输出实现方案

要实现你需要的菜单格式输出,只需在现有代码基础上做几个简单调整:

  • 新增整数计数器,给匹配到的水果结果编序号
  • 修改循环内的输出语句,按[序号] 水果信息的格式打印
  • 循环结束后统一添加[序号] Back to Menu选项

修改后的完整代码如下:

public void searchFromList() {
    String color;
    System.out.print("Input the color: ");
    Scanner scan = new Scanner(System.in);
    color = scan.nextLine();
    boolean test = false;
    int count = 1; // 初始化结果计数器

    for (Fruit fruit: fruits) {
        if (fruit.getcolor().equals(color)) {
            // 按菜单格式打印匹配结果
            System.out.printf("[%d] %s%n", count, fruit);
            test = true;
            count++; // 每找到一个结果,计数器自增
        }
    }

    // 打印返回菜单选项
    System.out.printf("[%d] Back to Menu%n", count);

    if (!test){
        System.out.println();
        System.out.println("Sorry there is no " + color + " fruit in list");
    }
}

关键调整说明:

  1. 计数器count:从1开始,每匹配到一个水果就自增,保证结果序号连续
  2. 格式化输出:用System.out.printf便捷控制输出格式,%d对应整数序号,%s对应水果的字符串表示,%n是平台无关的换行符
  3. 统一返回选项:不管有没有匹配结果,最后都会显示返回菜单选项,符合菜单式交互逻辑

测试输入"green"时,输出将变为:

[1] 01 Pear
[2] 03 Watermelon
[3] Back to Menu

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 21:54:14