2

I'm looking for help correcting an exception error for 'string index out of range'. My code is supposed to take two strings as input from the user(string1 and string2) and create new strings that are parts of the originals.

So far I have the following:

modString1 = string1.substring(string1.length() -3, string1.length());

modString2 = string2.substring(0,3);

The above code is supposed to take the last 3 characters of string1 and the first 3 characters of string2. The problem I am having comes when the user inputs a string that is shorter than 3 characters.

I'm wondering if there is a way to check the input and add a character (x for example) if the string is too short?

For example, if the user enters 'A' for the first string it will change the string to 'xxA' and if 'A' is entered for the second string it will change that to 'Axx'?

Mat
  • 188,820
  • 38
  • 367
  • 383
User2
  • 21
  • 1
  • 4

3 Answers3

1

Put an if statement before your code, checking the length of the string before you process it.

For example:

if(string1.length() < 3) {
    // Add characters to the string
}
Jonathon Ashworth
  • 1,164
  • 10
  • 19
1

I'm wondering if there is a way to check the input and add a character (x for example) if the string is too short?

What you are looking for is called padding.

It can be done in a number of ways. The simplest is probably to use an external library such as Apache's StringUtils. You could also write a padding method yourself using a StringBuilder.

Related:

Community
  • 1
  • 1
Mark Byers
  • 719,658
  • 164
  • 1,497
  • 1,412
  • This looks like what I had in mind except that the example used contains a known string ex: String.format("%10s", "foo").replace(' ', '*'); I'm not sure how to approach this if I am accepting input from the user which would replace "foo" in the example. – User2 Sep 19 '12 at 05:03
  • Change "foo" to the user input. – Mark Byers Sep 19 '12 at 05:11
  • I guess I'm just not sure how to do that. When I substitute the name of the input variable(string1) for "foo" I still get the out of range exception for String.format("%3s", string1).replace(' ', '*'); – User2 Sep 19 '12 at 05:35
  • You need to pad **before** calling substring. – Mark Byers Sep 19 '12 at 06:21
0

put the validation like below and add the string. For ex.

if(string1.length()<3){     
      String op = 'xx'; 
      string1 += op;
}
Dinup Kandel
  • 2,389
  • 4
  • 19
  • 36