Caesar Cipher代码错误:字符串索引超出范围

时间:2017-04-23 23:57:27

标签: java stringindexoutofbounds

我为我的11年级计算机科学课做了Caesar Cipher任务。我多次查看我的代码,改变它,但我没有做任何工作,我不明白为什么。

它给我的错误是java.lang.StringIndexOutOfBoundsException

import java.util.*;

//Caesar Cipher
public class CCTry1
{
    public static void main (String [] args)
    {
        //scanner
        Scanner scanner = new Scanner(System.in);
        Scanner scanner2 = new Scanner(System.in);


        //make an array with all the letters
        char[] alphabet = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};

        //prompt user for a message
        System.out.println("Enter your message.");
        String message = scanner.nextLine();

        //*******ENCRYPTING******

        System.out.println("Enter your shift number.");
        int shift = scanner2.nextInt();

        //find index of each letter of the user's message, then add the shift number
        //to obtain the new message

        char newletter;
        //for loop to encrypt
        for(int i=0; i<26; i++)
        {

            //take the i letter
            char letter = message.charAt(i);

            //check if that letter = a
            if (letter == alphabet[i])
            {

                //if letter = a, then the new letter is a+shift
                newletter = alphabet[i+shift];

                //if letter is capitalized, convert it to a capital then print
                if(Character.isUpperCase(letter))
                {
                    System.out.print(Character.toUpperCase(newletter));
                }
                //else, just print it as is
                else
                {
                    System.out.print(newletter);
                }
            }


        }
    }
}

1 个答案:

答案 0 :(得分:0)

你的问题是你的转变逻辑。例如,如果您尝试将z换算为5,则索引将超出范围。你需要在那时“环绕”。例如,将z移动2实际上应该导致b(索引1),索引27。

此外,您的for循环没有意义,因为它只有在message长度正好为26个字符时才有效。

你应该迭代消息中的字母,移动每个字母。确保你“环绕”。此外,不需要字母数组。

还有一个提示:模块化算术在这里可以派上用场。