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

Java实验9.18:解析用户输入至ArrayList时遇技术问题

问题分析与解决方案

你的代码核心问题出在输入读取方式上:使用scnr.next()只会读取单个空格分隔的单词,而非整行输入。这导致每次循环中input只拿到一行的第一个元素(比如第一行的plant),调用split(" ")后数组长度仅为1,后续访问info[1]、info[2]必然触发数组越界异常,无法正确解析完整的植物/花卉信息。

修复步骤

1. 更换输入读取方式

将scnr.next()改为scnr.nextLine(),确保每次读取完整的一行输入,同时用trim()去除首尾空白,避免空行或换行符干扰判断。

2. 调整循环逻辑

  • 先读取整行并判断是否为-1,是则退出循环
  • 对非-1的行,用\\s+作为分隔符分割(匹配任意数量空白字符,兼容多空格输入)
  • 根据分割后的第一个元素判断类型,分别创建Plant或Flower对象

3. 修正细节问题

  • 修正变量名拼写错误:colorOfFLowers改为colorOfFlowers
  • 用equalsIgnoreCase()替代toLowerCase().equals(),忽略大小写判断更鲁棒
  • 若plantCost是数值类型(如int),需将info[2]转换为对应类型后再调用setPlantCost(根据你的类实现调整)

修改后的完整代码

import java.util.Scanner;
import java.util.ArrayList;

public class PlantArrayListExample {

    // 打印ArrayList中所有植物/花卉信息
    public static void printArrayList(ArrayList<Plant> myGarden) {
        for (Plant item : myGarden) { // 增强for循环更简洁
            item.printInfo();
        }
    }

    public static void main(String[] args) {
        Scanner scnr = new Scanner(System.in);
        String input;
        ArrayList<Plant> myGarden = new ArrayList<Plant>();

        // 读取第一行输入并去除首尾空白
        input = scnr.nextLine().trim();

        while (!input.equals("-1")) {
            String[] info = input.split("\\s+"); // 匹配任意空白字符分割

            if (info[0].equalsIgnoreCase("plant")) {
                Plant p1 = new Plant();
                p1.setPlantName(info[1]);
                // 若Plant的setPlantCost接受int类型,需转换:p1.setPlantCost(Integer.parseInt(info[2]));
                p1.setPlantCost(info[2]);
                myGarden.add(p1);
            } else if (info[0].equalsIgnoreCase("flower")) {
                Flower f1 = new Flower();
                f1.setPlantName(info[1]);
                // 根据类实现调整plantCost的类型转换
                f1.setPlantCost(info[2]);
                f1.setPlantType(Boolean.parseBoolean(info[3]));
                f1.setColorOfFlowers(info[4]);
                myGarden.add(f1);
            }

            // 读取下一行输入
            input = scnr.nextLine().trim();
        }

        printArrayList(myGarden);
        scnr.close(); // 关闭Scanner释放资源
    }
}

关键说明

  • split("\\s+"):解决输入中多空格导致的分割异常,确保每个元素都是有效信息
  • trim():避免空行或换行符被误判为有效输入
  • 增强for循环:遍历集合代码更简洁,可读性更强

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 05:25:17