Scanner user_input = new Scanner( System.in ); String cipher_input = user_input.nextLine(); String[] arr_cipher_input = cipher_input.split(""); int[] arr_ctext = new int[cipher_input.length()]; for (int i = 0; i < cipher_input.length(); i++) { arr_ctext[i] = (int) arr_cipher_input[i].charAt(i); }
上面的代码接受一个输入并将其拆分为一个数组(例如,“hello”变为[“h”、“e”、“l”、“l”、“o”),然后我尝试将字符转换为ascii值,在ascii值中返回标题中的错误。它每次都正确地转换第一个字符,然后在第二个字符上停止,我似乎不知道为什么。数组长度似乎是一样的,所以我不确定我做错了什么。如果有任何帮助,我将不胜感激。提前感谢!
您正在创建一个字符的数字 String (s) 。但您正在尝试访问后续字符。没有了。改变 charAt(i) 到 charAt(0) 修复。喜欢
String
charAt(i)
charAt(0)
arr_ctext[i] = (int) arr_cipher_input[i].charAt(0);
或 (更有效)跳过 split 并直接访问输入中的字符。喜欢
split
String cipher_input = user_input.nextLine(); int[] arr_ctext = new int[cipher_input.length()]; for (int i = 0; i < cipher_input.length(); i++) { arr_ctext[i] = (int) cipher_input.charAt(i); }