1

I'm stuck with this and can't find a solution. Get error of Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 11.

Can anyone help to solve this? My code:

public static void main(String[] args) {
    try {
        Scanner sc = new Scanner(new File("Testing.txt"));
        int i = 0;

        while(sc.hasNext()){
            String line = sc.nextLine();
            char needle = line.charAt(i);

            while(i < line.length()){
                if(Character.isUpperCase(needle)) {
                    while(needle != ' '){
                        System.out.print(needle);
                        i++;
                        needle = line.charAt(i);
                    }
                    System.out.println(needle);
                }
                else{
                    i++;
                    needle = line.charAt(i);
               }
            }
        }
    } 
    catch (FileNotFoundException e) {
        System.out.println(e.getMessage());
    }
}
5
  • 1
    what are you actually trying to do? Commented Mar 13, 2017 at 8:09
  • I'm trying to get all the strings that contains capital letter from the input text file. E.g. input text file contains "Kenny and I are eating in the Restaurant Yummy.". The output will be "Kenny, I, Restaurant, Yummy". Commented Mar 13, 2017 at 8:40
  • use split to split your line into word and test the first char to see if starts with uppercase Commented Mar 13, 2017 at 8:42
  • Any examples that I can refer to? Thanks. Commented Mar 13, 2017 at 8:46
  • K.W I have added an answer showing you how. Alot cleaner and easier to understand I think Commented Mar 14, 2017 at 0:50

3 Answers 3

1

My assumption is that your error would be here;

                i++;
                needle = line.charAt(i);

and

                while(needle != ' '){
                    System.out.print(needle);
                    i++;
                    needle = line.charAt(i);
                }

As you are increasing the index without checking if the index exists.

Sign up to request clarification or add additional context in comments.

2 Comments

Any idea of how to fix this? How to check whether if the index is exists from the above code?
Something like if(i < line.length()), as you have elsewhere.
0

As per my above comment, it will be easuer to use the String split method. Of course input can be replaced with text from the file, and use of expectedResult and testing that the output equals that is purely optional

  public static void main(String[] args)
  {

      String input = "Kenny and I are eating in the Restaurant Yummy";
      String expectedResult = "Kenny, I, Restaurant, Yummy";
      String arr [] = input.split (" ");

      StringBuilder out = new StringBuilder();
      for (int i = 0; i < arr.length; i++) {
          if (Character.isUpperCase(arr[i].charAt(0))) {
              out.append(arr[i]).append(", ");
          }
      }

      if (out.length() > 1) {
          out.setLength(out.length() -2);
      }

      System.out.println (out);
      assert (expectedResult.equals(out.toString()));

  }  

output

Kenny, I, Restaurant, Yummy

2 Comments

May I know what is this line do? if (out.length() > 1) { out.setLength(out.length() -2); }
because we are appending ", " to every occurrence, we want to remove the last one.
0

I'm not sure what you are trying to achieve. But from your error, I can say that you are trying to increment the index counter and then trying to access the element in your String.

Inside your while loop and the else block, you have these statements:

i++;
needle = line.charAt(i);

Change them both to:

needle = line.charAt(i);
i++;

And your code will run without the said exception.

Update

I did the changes mentioned above, and made a couple of changes.

  1. Include the declaration for int i=0; inside the first while loop. This is needed for more than one line in the text file.
  2. Include the declaration char needle = line.charAt(i); statement inside the second while loop as you need to initialize needle for each line.

try (Scanner sc = new Scanner(new File("Testing.txt"))) {

    while (sc.hasNext()) {
        String line = sc.nextLine();
        int i = 0;

        while (i < line.length()) {
            char needle = line.charAt(i);
            if (Character.isUpperCase(needle)) {
                while (needle != ' ' && i < line.length()) {
                    needle = line.charAt(i);
                    if(needle != ' '){
                        System.out.print(needle);
                    }
                    i++;
                }
                if(i < line.length()) {
                    System.out.print(", ");
                }
            } else {
                needle = line.charAt(i);
                i++;
            }
        }
        System.out.println();
    }
} catch (FileNotFoundException e) {
    System.out.println(e.getMessage());
}

It prints the following output:

Kenny, I, Restaurant, Yummy

Hope this helps!

1 Comment

I'm trying to get all the strings that contains capital letter from the input text file. E.g. input text file contains "Kenny and I are eating in the Restaurant Yummy.". The output will be "Kenny, I, Restaurant, Yummy". I have try to change them both according to the solution you suggest, but still getting the same error.

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.