首页 > 解决方案 > 我无法让任何 indexOf() 函数为我编写的这段代码工作

问题描述

package Captain_Ship.alphanum;
import org.apache.commons.lang3.ArrayUtils;
import java.util.Arrays;

public class A2N {
    public static String main(String input) {
        char[] alphabet = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y','z'};
        String output = "";
        char[] input_char = input.toLowerCase().toCharArray();
        int[] output_int = {};

        //Still doesn't work. outputs [I@123772c4 in place of 8 5 12 12 15
        for (int i = 0; i>input_char.length; i++) {
            output_int[i] = ArrayUtils.indexOf(alphabet,input_char[i]);
        }
        output = Arrays.toString(output_int);
        return output;
    }
}

这是我的代码。它的目标非常简单。取一个句子并将每个字母翻译成一个数字。所以 A 会是 1,B 会是 2,等等。我已经尝试了一切来尝试让循环按我想要的方式工作。这段代码是目前唯一给我其他东西的版本,而不是类似的东西:[I@123772c4. 我已经用完了我研究过的选项。

标签: javaarraysindexof

解决方案


  1. List如果您不知道数组的大小,例如您不知道的大小,请使用 a而不是数组output_int,因此最好使用动态数组类型的对象,例如List.
  2. 您也可以使用 aList来存储字符。List是 Java 集合 API 的一部分,这样您就不必org.apache.commons.lang3.ArrayUtils像查找元素索引之类的操作那样使用 3rd 方库。
  3. 你的循环应该检查i < input_char.length而不是i > input_char.lengthwhich will never be true

演示:

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        // List of alphabets
        List<Character> alphabet = List.of('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
                'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');

        // A sample string
        String input = "sample string";

        char[] input_char = input.toLowerCase().toCharArray();

        // List to store the index of each character of `input` in `alphabet`. Note: if
        // a character is not found, the indexOf method returns -1
        List<Integer> output_int = new ArrayList<>();

        for (int i = 0; i < input_char.length; i++) {
            output_int.add(alphabet.indexOf(input_char[i]));
        }

        // Display the list
        System.out.println(output_int);
    }
}

输出:

[18, 0, 12, 15, 11, 4, -1, 18, 19, 17, 8, 13, 6]

推荐阅读