Chrissy
Chrissy

Reputation: 19

StringIndexOutOfBoundExceptions error is showing

I am trying to make an acronym from the three words that is input by the user:

 import java.util.Scanner;
 public class Acronym
 {
    public static void main(String[] args)
    {    

       Scanner input = new Scanner(System.in);
       String phrase;
       System.out.println("Please, enter the three words here>> ");
       phrase = input.nextLine();     
       char first, second, third;
       int stringLength;
       int x = 0;
       char c;
       stringLength = phrase.length();
       first = phrase.charAt(0);
       second = phrase.charAt(x + 1);
       third = phrase.charAt(x + 1);

          for( x = 0; x < stringLength; x++);
          {
             int a = 1;
             c = phrase.charAt(x);

             if(Character.isWhitespace(c));
               if( a <= 1)
                second = phrase.charAt(x+1);

             else if(a <= 2)
                third = phrase.charAt(x++);
          }

      System.out.println("The acronym is " + first + second + third);
   }

 }

But, whenever I try to input StringIndexOutOfBoundExceptions error is showing. For example I tried to input the three words "One Two Three" and this is the result:

Please, enter the words/phrases: One Two Three

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 13 at java.lang.String.charAt(String.java:646) at Acronym.main(Acronym.java:23)

Upvotes: 0

Views: 92

Answers (1)

Reimeus
Reimeus

Reputation: 159864

Remove the semi-colon

for (x = 0; x < stringLength; x++);
                                  ^

which is terminating the for loop. Same for the semi-colon terminating the if statement

if (Character.isWhitespace(c));
                              ^

and please use braces to surround control blocks

Upvotes: 2

Related Questions