Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/ant/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 为什么我会得到一个“a”;字符串索引超出范围:53“;错误?_Java_String - Fatal编程技术网

Java 为什么我会得到一个“a”;字符串索引超出范围:53“;错误?

Java 为什么我会得到一个“a”;字符串索引超出范围:53“;错误?,java,string,Java,String,我正在尝试使用我们在学校学到的一些基本代码制作一个加密机。我已经设法找到了某个地方(我想),但出于某种原因,我似乎使这个“字符串索引超出范围:53”错误。谁能告诉我为什么 public void Encryption() { String Password = "CodingIsHard"; String answer = ""; for (int i = 0; i < Password.length(); i++) { answer = Chara

我正在尝试使用我们在学校学到的一些基本代码制作一个加密机。我已经设法找到了某个地方(我想),但出于某种原因,我似乎使这个
“字符串索引超出范围:53”
错误。谁能告诉我为什么

public void Encryption() {
    String Password = "CodingIsHard";
    String answer = "";
    for (int i = 0; i < Password.length(); i++) {
        answer = Character.toString(Password.charAt(i + '5'));

    }
    System.out.println(answer);
}

public static void main(String[] args) {
    PasswordGenerator GP = new PasswordGenerator();
    GP.Encryption();
}
public void Encryption(){
字符串Password=“CodingIsHard”;
字符串答案=”;
对于(int i=0;i
'5'
是一个字符,而不是数字5。在ASCII中,字符
5
的值为53,因此当
i
为零时,您试图访问索引
0+53
,这超出了字符串的范围。您可能希望将加法移到
charAt()
括号之外。

'5'
是一个字符,而不是数字5。在ASCII中,字符
5
的值为53,因此当
i
为零时,您试图访问索引
0+53
,这超出了字符串的范围。您可能希望将添加内容移到
charAt()
括号之外。

如果要将
'5'
添加到要由
charAt()
检索的索引中,请将代码更改为:

public void Encryption() {
    String Password = "CodingIsHard";
    String answer = "";
    for (int i = 0; i < Password.length(); i++) {
        answer = Character.toString(Password.charAt(i) + '5');

    }
    System.out.println(answer);
}

public static void main(String[] args) {
    PasswordGenerator GP = new PasswordGenerator();
    GP.Encryption();
}
public void Encryption(){
字符串Password=“CodingIsHard”;
字符串答案=”;
对于(int i=0;i
如果要将
'5'
添加到要由
charAt()检索的索引中,请将代码更改为:

public void Encryption() {
    String Password = "CodingIsHard";
    String answer = "";
    for (int i = 0; i < Password.length(); i++) {
        answer = Character.toString(Password.charAt(i) + '5');

    }
    System.out.println(answer);
}

public static void main(String[] args) {
    PasswordGenerator GP = new PasswordGenerator();
    GP.Encryption();
}
public void Encryption(){
字符串Password=“CodingIsHard”;
字符串答案=”;
对于(int i=0;i
使用charAt时要小心。您的字符串“CodingIsHard”只有12个字母,而您在For循环中所做的总和可以使该数字高于字符串中的字母数。例如,如果i=10,你求和5,i=15。在12个字母的字符串中没有15个位置!此外,Java在其ASCII值53中考虑了您的“5”。考虑使用一个整数值(除非这是你的意图)。您的字符串“CodingIsHard”只有12个字母,而您在For循环中所做的总和可以使该数字高于字符串中的字母数。例如,如果i=10,你求和5,i=15。在12个字母的字符串中没有15个位置!此外,Java在其ASCII值53中考虑了您的“5”。考虑使用整数值(除非这是你的意图)。

因为i+' 5,no .nb:单引号使情况更糟。<代码> '5'/COD>是一个值为0x35=53的ASCII字符,因为I+' 5,NO .NB:单引号使情况更糟。<代码> '5' /COD>是一个0x35=53的ASCII字符。