Fixing a out of bound error while doubling all the letters except the first and the last letters

This code should double all but the first and last letter in message. Fix the code so that it doesn’t cause an out of bounds error. I can’t figure out where i am going wrong.

public class Loop2
{
public static void main(String[] args)
{
  String result = "";
  String message = "watch out";
  int pos = 0;
 while (pos < message.length())
   {
      result = result + message.substring(pos,pos+2);
      pos = pos + 1;
   }
   System.out.println(result);

} }

Answer

It’s because your condition is :

pos < message.length()

So when you do :

message.substring(pos,pos+2);

It will throw an out of bound exception beacause pos will be 1 + message.length().

A solution is to change your condition to

pos < message.length() - 1

Or is to use the charAt() function. charAt(i) return the character in a String at the index i

Leave a Reply

Your email address will not be published. Required fields are marked *