java - 我无法让任何 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. 我已经用完了我研究过的选项。
解决方案
List
如果您不知道数组的大小,例如您不知道的大小,请使用 a而不是数组output_int
,因此最好使用动态数组类型的对象,例如List
.- 您也可以使用 a
List
来存储字符。List
是 Java 集合 API 的一部分,这样您就不必org.apache.commons.lang3.ArrayUtils
像查找元素索引之类的操作那样使用 3rd 方库。 - 你的循环应该检查
i < input_char.length
而不是i > input_char.length
which will never betrue
。
演示:
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]
推荐阅读
- javascript - 有没有一种方便的方法可以在放置请求后将状态从子组件传递到子组件,或者在这种情况下我是否必须开始使用 Redux?
- postgresql - 带有 Postgres 的 ProFTPD
- window - 在 Windbg 断点后执行命令不起作用?
- python - selenium.common.exceptions.SessionNotCreatedException:ChromeDriver 仅支持 Chrome 版本 84
- python - 锚文本 Python CLI 输出
- r - 内部时间 Shinyproxy UTC
- cmake - 自定义源文件中的动态依赖关系
- javascript - 计算网站的页面浏览量和唯一浏览量
- c# - 为winForm设置可见时的跨线程
- r - R 中的 format() 函数不能使用相同的参数根据使用的数据提供不同的输出