This program does what I want it to do but it also outputting a massive big error. Which says something like "array out of bounds. string index out of bounds". The program is meant to take an input of a sentence and rewrite it using different letters (4 characters up) from the alphabet. Please help me clear up this error!
public class Encryption
{
public static void main (String [] args)
{
System.out.print("Enter a message to encrypt: ");
String input = Console.readString();
for(int i = 0; i<100; i++)
{
char oldChar = input.charAt(i);
char encryptedChar = (char) (oldChar + 4);
System.out.print(encryptedChar);
}
}
If you get a StringIndexOutOfBoundsException
, then your input isn't 100 characters long.
Don't expect 100 characters; stop your for
loop when i
reaches your string's length.
for (int i = 0; i < input.length(); i++)
Is the input always a 100 character string, I believe not and that's the error. Replace 100 with input.length()
Change your loop bounds. You're looping from i=0 to i=99 which will exceed the input length if the user types less than 100 characters.
for (int i = 0; i < input.length(); i++)
As previously stated you hard coded the loop to iterate 100 chars. What if the string isn't 100 char
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.