朝鲜蓟密码程序给我字符串索引超出范围错误

时间:2011-10-14 15:14:39

标签: java windows

我必须制作一个java程序(朝鲜蓟密码)...请帮助lol

它一直给我一个错误 -

 "
    java.lang.StringIndexOutOfBoundsException: String index out of range: 11
    at java.lang.String.charAt(String.java:686)
    at ArtichokeCipher.main(ArtichokeCipher.java:29)
    "

这是实际的朝鲜蓟密码程序。我从用户那里获取数据文件然后询问他们用于从文本文件内的数据中移位字母的密钥。从那里我将密码密钥转换成一个字符,用作一个转移号码,但我真的丢失了为什么我得到这个错误。

//PROGRAM
import java.util.Scanner;
import java.io.*;

public class ArtichokeCipher {
public static void main(String[] args) throws IOException {
    Scanner scan1 = new Scanner (System.in);

    System.out.println("Welcome to Artichoke Cipher!");
    System.out.println("Please name input file to be processed: ");
    String filei = scan1.next();
    Scanner scan = new Scanner (new File (filei));

    System.out.println("Please enter the word to be used as the cipher key: ");
    String shift = scan1.next();
    String lowcase = shift.toLowerCase();


    while (scan.hasNext()) {
    String word = scan.nextLine();
    String answer = "";
    for (int i = 0; i < word.length(); i++)
    {
       char curChar = word.charAt(i);
       char key = lowcase.charAt(i);
       char newChar = (char)(curChar + key);
       if (curChar >= 'A' && curChar <= 'Z'){
           if (newChar > 'Z')
           newChar = (char)(newChar-26);
        }
        else if (curChar >= 'a' && curChar <= 'z') {
            if (newChar > 'z')
            newChar = (char)(newChar - 26);
    }
}
            System.out.println("Encoded: " + answer);
}
}
}

感谢任何帮助

1 个答案:

答案 0 :(得分:0)

您可能会超越此行上的字符串:

char key = lowcase.charAt(i);

原因是索引iword有效,但可能超出lowcase的长度。在这种情况下,当word超过lowcase时,您可以获得Out of Bounds异常。