[英]ArrayIndexOutOfBoundsException after splitting a string
尝试将此代码提交到https://www.hackerrank.com/challenges/contacts/problem上的 hackerrank 时出现以下错误:
线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException:1 在 Result.contacts(Solution.java:31)在 Solution.main(Solution.java:66)
不过在我本地机器上好像可以,但是我不确定分词后会不会有问题。 当我通过调试检查时,它似乎被正确地分割了,但我不确定分割后是否需要使用额外的检查。 或者拆分可能有问题。
public static void main(String[] args) {
List<String> s = List.of("add hack", "add hackerrank", "find hac", "find hak");
List<List<String>> queries = Collections.singletonList(s);
List<Integer> result = contacts(queries);
result.forEach(System.out::println);
}
public static List<Integer> contacts(List<List<String>> queries) {
Set<String> set = new HashSet<>();
List<Integer> result = new ArrayList<>();
for (List<String> query : queries) {
for (String s : query) {
// !!! the problem may be caused from these lines >>>
String operation = s.split(" ")[0];
String word = s.split(" ")[1];
if (operation.equals("add")) {
set.add(word);
} else if (operation.equals("find")) {
long count = set.stream().filter(c -> c.startsWith(word)).count();
result.add((int) count);
}
}
}
return result;
}
那么,问题的原因可能是什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.