0

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);
}   
}
1
  • 1
    What part of the error don't you understand? Hint: When should your loop stop? Commented Dec 3, 2013 at 19:42

4 Answers 4

1

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++)
Sign up to request clarification or add additional context in comments.

Comments

1

Is the input always a 100 character string, I believe not and that's the error. Replace 100 with input.length()

Comments

0

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++)

Comments

0

As previously stated you hard coded the loop to iterate 100 chars. What if the string isn't 100 char

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.