【发布时间】:2019-05-08 01:31:55
【问题描述】:
作业:获取两个字符串,用逗号分隔。保存到哈希图。
目标:使用单个 try-catch 块来防止用户输入错误数量的字符串。
问题:如果只提供一个字符串,register.put 行将抛出“IndexOutOfBounds”,但如果我提供 3+ 个字符串,看起来我的数组的大小正在增加以处理附加行项目(根据 IntelliJ IDEA 中的调试器)。这是 nextLine().split 函数的预期功能还是我遗漏了一些明显的东西?我知道我可以使用另一个循环来纠正这个问题,但我对“收集器”如何处理以下输入感到困惑:
Hello,World,Isn't,It,A,Great,Day?
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!");
}
【问题讨论】:
-
数组对象没有改变大小。相反,当您调用
collector = in.nextLine().split(",");时,会为收集器变量分配一个 new 数组。之前的 2 项空数组被丢弃和浪费了。 -
split() 方法返回一个 String[]。所以原本大小为 2 的收集器 [] 数组将被重新分配 split 方法返回的 String[]。
-
异常的原因很可能是发生异常时您正在阅读的行不是您认为的那样。调试它——找出到底是哪一行。