我正在为我 11 年级的计算机科学课做凯撒密码作业。我多次查看我的代码,更改它,但我没有做任何工作,我不明白为什么。
它给我的错误是 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);
}
}
}
}
}