i have to make a java program (an artichoke cipher) well... please help lol
it keeps giving me an error -
"
java.lang.StringIndexOutOfBoundsException: String index out of range: 11
at java.lang.String.charAt(String.java:686)
at ArtichokeCipher.main(ArtichokeCipher.java:29)
"
this is the actual artichoke cipher program..i obtain the data file from the user then ask them for the key to be used to shift the letters from the data inside the text file. From there i turn the cipher key into a char to be used as a shift number but im just really lost as to why i get this error.
//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);
}
}
}
any help is appreciated thanks
You are potentially overrunning a string on this line:
char key = lowcase.charAt(i);
The reason is that the index i
is valid for word
, but may be beyond the length of lowcase
. In which case, you will can an Out of Bounds exception when word
is longer than lowcase
.
精彩评论