import java.util.*;
public class Kata {
public static void main(String[]args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter a text to encrypt:");
//to read the whole line
String text = scan.nextLine();
System.out.println(encryptThis(text));
}
public static String encryptThis(String text) {
//words are separated by just one white space between them.
//In order to split it and get the array of words, just call the split()
String [] array = text.split("");
String encrypt = "";
for(int j = 0; j < array.length;j++)
{
String test = array[j];
//get first character
char first = test.charAt(0);
//convert the first character into ASCII code;
int ascii = (int) first;
encrypt+=ascii;
char second = test.charAt(1);
char last = test.charAt(test.length()-1);
encrypt+=last;
for(int i = 2; i < text.length()-1;i++)
{
encrypt+=test.charAt(i);
}
encrypt+=second + " ";
}
return encrypt;
}
}
线程 "main "中的异常 java.lang.StringIndexOutOfBoundsException。String index out of range: 1我不知道为什么我的索引超出了范围,请帮助我,我正试图写一个程序来加密信息。
String test = array[j];
只取数组中的第j个字符,并对其进行加密。test.charAt(1)
会使代码失败。围绕这一点写几条打印语句来进一步调试
在访问该位置的字符前添加一个检查
char second = null;
if(test.length > 1) {
second = test.charAt(1);
}