首页 > 解决方案 > 在 Java 中使用字符串拆分时数组大小发生变化

问题描述

作业:获取两个字符串,用逗号分隔。保存到哈希图。

目标:使用单个 try-catch 块来防止用户输入错误数量的字符串。

问题:如果只提供一个字符串,则register.put行将抛出“IndexOutOfBounds”,但如果我提供 3+ 个字符串,看起来我的数组的大小正在增加以处理额外的行项目(根据 IntelliJ 中的调试器主意)。这是nextLine().split函数的预期功能还是我遗漏了一些明显的东西?我知道我可以使用另一个循环来纠正这个问题,但我很困惑“收集器”如何处理以下输入:

你好,世界,不是,它,A,伟大的,一天吗?

    HashMap <String, String> register = new HashMap();
    Scanner in = new Scanner(System.in);
    String[] collector = new String[2];


        try {
            collector = in.nextLine().split(",");
            register.put(collector[0], collector[1]);
        }catch (IndexOutOfBoundsException e){
            System.out.println("\nYou didn't use the correct format!");
            System.out.println("Please use the format provided!");
        }

标签: javaarrayssplithashmap

解决方案


尝试处理错误的输入而不是捕获异常。

HashMap <String, String> register = new HashMap();
Scanner in = new Scanner(System.in);


String[] collector = in.nextLine().split(",");

// validate inputs here
if (collector.length == 2 ) {
    register.put(collector[0], collector[1]);
} else {
    System.out.println("\nYou didn't use the correct format!");
    System.out.println("Please use the format provided!");
}

推荐阅读