簡體   English   中英

拆分字符串后出現 ArrayIndexOutOfBoundsException

[英]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;
}

那么,問題的原因可能是什么?

您的問題是您如何解釋“查詢”是什么。 OperationWord不在一個 String 中。 它們是查詢中的元素。 所以...

for (List<String> query : queries) {
    String operation = query.get(0);
    String word = query.get(1);
    // The rest of your code;
}

在此處輸入圖像描述

這是為那些喜歡發表評論而不先嘗試自己的建議的人准備的。 在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM