java - 在 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!");
}
解决方案
尝试处理错误的输入而不是捕获异常。
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!");
}
推荐阅读
- python - 在 p 中获取不在另一个 p 中的文本
- c++ - 如何搜索 utf8 字符?
- go - go 模板和制表符
- flutter - Flutter:热重启会使应用程序崩溃,但冷重启不会(因为记录器已经初始化)
- firebase - 如何知道 Firestore 分页中的下一个块是否为空?
- javascript - 如何处理 Node.js 上的动态页面
- r - 按平均值组合 R 中的多个数据帧(混合数据类型)
- apache - segine 2.7.1 - domain.com 之后的问题双斜杠//
- python - 如何使用 Python 在条形图中表示二维分类数据
- airflow - Airflow dag_id 不存在或解析失败