[英]String Index out of range: 1
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值,即返回標題錯誤的位置。 每次它都能正確轉換第一個字符,然后在第二個字符上停止,我似乎無法弄清楚為什么。 數組長度似乎相同,所以我不確定自己在做什么錯。 我將不勝感激。 提前致謝!
您正在創建多個一個字符的String
。 但是您正在嘗試訪問后續字符。 沒有啊 將charAt(i)
更改為charAt(0)
進行修復。 喜歡,
arr_ctext[i] = (int) arr_cipher_input[i].charAt(0);
或 (更有效地)跳過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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.