[英]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.